2012-12-24 143 views
0

我試圖將文件下載到我的計算機上的任何位置,但是當我單擊該按鈕時它會將它發送到我的下載文件夾。我使用的代碼如下:下載文件ASP.NET C#

我希望能夠選擇「桌面,我的文檔,ETC」。我究竟做錯了什麼?

protected void Button1_Click(object sender, EventArgs e) 
{ 
    // The file path to download. 
    string filepath = @"C:\Test\Test.docx"; 
    // The filename used to save the file to the client's system.. 
    string filename = Path.GetFileName(filepath); 
    Stream stream = null; 
    try 
    { 
     // Open the file into a stream. 
     stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, 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(); 
     } 
    } 
} 
+0

contentType中應設置爲我以爲Microsoft Word文檔'應用/ msword'。 – Seany84

+0

可能重複的[如何在asp.net中實現文件下載](http://stackoverflow.com/questions/37650/how-to-implement-a-file-download-in-asp-net) – jball

回答