SoFunction
Updated on 2025-04-06

(c#) file download implementation code

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
public partial class _Default :
{
protected void Page_Load(object sender, EventArgs e) { }
//TransmitFile implementation download
protected void Button1_Click(object sender, EventArgs e)
{
/* Microsoft provides a new method for Response objects TransmitFile to solve the problem that the Aspnet_wp.exe process cannot be successfully downloaded when downloading files exceeding 400mb. The code is as follows: */
= "application/x-zip-compressed"; ("Content-Disposition", "attachment;filename=");
string filename = ("DownLoad/"); (filename);
}
//WriteFile implementation download
protected void Button2_Click(object sender, EventArgs e)
{
/* using ; */
string fileName = "";//The file name saved by the client
string filePath = ("DownLoad/");//Path
FileInfo fileInfo = new FileInfo(filePath);
();
();
();
("Content-Disposition", "attachment;filename=" + fileName); ("Content-Length", ());
("Content-Transfer-Encoding", "binary");
= "application/octet-stream";
= ("gb2312");
();
();
();
}
//WriteFile chunked download
protected void Button3_Click(object sender, EventArgs e)
{
string fileName = "";//The file name saved by the client
string filePath = ("DownLoad/");//Path
fileInfo = new (filePath);
if ( == true)
{
const long ChunkSize = 102400;//100K Each time you read the file, only 100K is read, which can relieve the pressure on the server.
byte[] buffer = new byte[ChunkSize];
();
iStream = (filePath);
long dataLengthToRead = ;//Get the total size of the downloaded file
= "application/octet-stream";
("Content-Disposition", "attachment; filename=" + (fileName)); while (dataLengthToRead > 0 && )
{
int lengthRead = (buffer, 0, Convert.ToInt32(ChunkSize));//Read size (buffer, 0, lengthRead);
();
dataLengthToRead = dataLengthToRead - lengthRead;
}
();
}
}
//Download streaming method
protected void Button4_Click(object sender, EventArgs e)
{
string fileName = "";//The file name saved by the client
string filePath = ("DownLoad/");//Path //Download the file in the form of a character stream
FileStream fs = new FileStream(filePath, );
byte[] bytes = new byte[(int)]; (bytes, 0, );
();
= "application/octet-stream"; //Not the browser to download the file instead of opening it ("Content-Disposition", "attachment; filename=" + (fileName, .UTF8));
(bytes);
();
();
}
}

/*
Here are 4 common download methods for reference introduction:
This article introduces some basic knowledge of Internet communication programming using C# through an example. We know that the .Net class includes request/response layer, application protocol layer, transport layer and other levels. In this program, we use the WebRequest class and WebClient class located in the request/response layer to implement high abstraction Internet communication services. The function of this program is to complete the download of network files.
Implementation principle
The principle of program implementation is relatively simple, mainly using the WebClient class and FileStream class. The WebClient class is in the name space. The main function of this class is to provide a public method to send data to URI-identified resources and receive data from URI-identified resources. We use the DownloadFile() method in it to download the network file locally. Then use the instance object of the FileStream class to write the file data to the local file in a data stream. This completes the download of network files.
Implementation steps
First, open Visual and create a new Visual C# Windows application project, and might as well name it "MyGetCar". Next, arrange the main interface. Let's first add the following controls to the main form: two label controls, two text box controls, a button control, and a status bar control.
Set the properties of each control as follows:
Control type Control name Property type Property value Main form Form1 Text property File downloader Label control Label1 Text property File address: TextAlign property MiddleRight Label2 Text property Save to: TextAlign property MiddleRight Text box control srcAddress Text property (empty) tarAddress Text property (empty) Button control Start FlatStyle property Flat Text property Start download StatusBar Text property (empty)
Other properties can be default values, and the final main form is shown in the figure below:
Complete the design of the main form, and then complete the code writing.
It is quite easy to write the code based on understanding the basic principles. We mainly use the WebClient class in the program, but before we call the instance object of the WebClient class, we need to use the WebRequest class object to issue a request to the Uniform Resource Identifier (URI).
Copy the codeThe code is as follows:

try { WebRequest myre=(URLAddress); }
catch(WebException exp){
(,"Error");
}

This is a try-catch statement. The try block completes the request to the URI, and the catch block catches possible exceptions and displays exception information. The URLAddress is the requested network host name. After the request is successful, we can use the DownloadFile() method in the instance object of the WebClient class to download the file. The function prototype is as follows: public void DownloadFile( string address, string fileName); where the parameter address is the URI from which data is downloaded, and fileName is the name of the local file to receive the data. Then we use the OpenRead() method to open a readable stream that completes the function of downloading data from a resource with a specified URI. The function prototype is as follows: public Stream OpenRead(string address); where the parameter address is the same as above. Finally, create a new StreamReader object to read the file data from it, and use a while loop body to continuously read the data until all the data is read.
Also when using the above method, you may need to deal with the following exceptions:
● WebException: An error occurred while downloading data.
● UriFormatException: The URI formed by combining BaseAddress, address and QueryString is invalid.
The code for this part is as follows: (client is a WebClient object, declared at the beginning of this class)
Copy the codeThe code is as follows:

= "Start downloading files...";
(URLAddress,fileName);
Stream str = (URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[100000];
int allmybyte = (int);
int startmbyte = 0;
= "Receiving data...";
while(allmybyte>0){
int m = (mbyte,startmbyte,allmybyte);
if(m==0)
break;
startmbyte+=m;
allmybyte-=m;
}

After completing the reading of file data, we use the instance object of the FileStream class to write the data to the local file:
FileStream fstr = new FileStream(Path,,); (mbyte,0,startmbyte);
*/