我正在尝试将文件下载到计算机上的任何位置,但是当我单击按钮时,它会直接将其发送到我的下载文件夹。我正在使用的代码如下:
我希望能够选择“桌面、我的文档、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();
}
}
}