2012-05-29

Force browser to download the file instead of opening it in the browser

Sometimes files such as images, videos, textfiles, XML files etc. are getting open in the browser window, when we give the download link directly to the file. To avoid that behavior and to force browser to download the file to the user’s computer when user clicks on the download link/button, we can use the below code on the button click event.

FileInfo fileInfo = new FileInfo("file_path_here");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.WriteFile(fileInfo.FullName);
Response.End();

No comments: