Está en la página 1de 5

 

// Get the physical Path of the file(test.doc)


   string filepath = Server.MapPath("test.doc");
   // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo file = new FileInfo(filepath);
  
   // Checking if file exists
   if (file.Exists)
   {
    // Clear the content of the response
    Response.ClearContent();
    
    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show,
to the header
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    
    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());
    // Set the ContentType
    Response.ContentType = ReturnExtension(file.Extension.ToLower());
    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use
WriteFile instead)
    Response.TransmitFile(file.FullName);
    // End the response
    Response.End();
   }
private string ReturnExtension(string fileExtension)
{
     switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
}

N.B:  If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below
code

Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

Response.TransmitFile VS Response.WriteFile: 
 1- TransmitFile: This method sends the file to the client without loading it to theApplication memory
on the server. It is the ideal way to use it if the file size being download is large.
 2- WriteFile: This method loads the file being download to the server's memory before sending it to
the client. If the file size is large, you might the ASPNET worker process might get restarted.

Hope this helps,


File Download in ASP.Net with C#

The following code can be used for downloading files in our application.The Original
path of the file will be hidden using this code.
private void btnDownload_Click(object sender, System.EventArgs e)
{
// The file path to download.
string filepath = @"C:\shadow_copy.rar";
// The file name used to save the file to the client's system..
string filename = Path.GetFileName( filepath );
System.IO.Stream stream = null; 
try
{
// Open the file into a stream. 
stream = new FileStream( filepath,
System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read ); 
// Total bytes to read: 
long bytesToRead = stream.Length; 
Response.ContentType = "application/octet-stream"; 
Response.AddHeader( "Content-Disposition", "attachment; filename=" + filename ); 
// Read the bytes from the stream in small portions. 
while ( bytesToRead > 0 ) 
{
// Make sure the client is still connected. 
if ( Response.IsClientConnected ) 
{
// Read the data into the buffer and write into the 
// output stream. 
byte[] buffer = new Byte[10000]; 
int length = stream.Read( buffer, 0, 10000 ); 
Response.OutputStream.Write(buffer, 0, length); 
Response.Flush(); 
// We have already read some bytes.. need to read 
// only the remaining. 
bytesToRead = bytesToRead - length;

else
{
// Get out of the loop, if user is not connected anymore.. 
bytesToRead = -1; 
}
}

catch(Exception ex) 
{
Response.Write(ex.Message); 
// An error occurred.. 
}
finally 
{
if ( stream != null ) { 
stream.Close(); 
}
}
}

También podría gustarte