简体   繁体   中英

File download in ASP.Net using C#

I am trying to make my client to download file from my website. I tried this code:

string fName = Server.MapPath((new_exwork.FilePath));
FileInfo fi = new FileInfo(fName);
long sz = fi.Length;
Response.ClearContent();
Response.ContentType = MimeType(Path.GetExtension(fName));
Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(fName)));
Response.AddHeader("Content-Length", sz.ToString("F0"));
Response.TransmitFile(fName);
Response.End();

But I get the following exception:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

MimeType function

private static string MimeType(string Extension)
    {
        string mime = "application/octetstream";
        if (string.IsNullOrEmpty(Extension))
            return mime;

        string ext = Extension.ToLower();
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (rk != null && rk.GetValue("Content Type") != null)
            mime = rk.GetValue("Content Type").ToString();
        return mime;
    } 

ok some suggestions.

One way is to just have a hyperlink to the file and with the client click on the file the browser will ask them if they want to download.

you can have them right click and do a save target to download.

If you are looking to track the status of downloads

Here is a link you can look at. FileDownload Tracking Status

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM