Reputation: 11
I am trying to download a file to any location on my computer, but it is sending it right to my downloads folder when I click the button. The code I am using is below:
I want to be able to chose "Desktop, My Documents, ETC". What am I doing wrong?
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();
}
}
}
Upvotes: 0
Views: 5579
Reputation: 66641
This have to do with your browser settings - What browser do you use ? What ever, go to the settings of your browser, locate the download options, and tell them to ask you where to save it first.
For google chrome: Change download locations
For Firefox: Change what Firefox does when you click on or download a file
Upvotes: 1