How Get File Name from URL ,C#/.NET?

我只是一个虾纸丫 提交于 2019-12-11 06:48:55

问题


How can I get a file name if the address ends with something like this.
/download/file/36fdd4aebda3819d329640ce75755657bc0c0d4c6811432b3bb6aac321dc78d/ ?

This is the simplified code example,

void geckoWebBrowser1_Navigating(object sender, GeckoNavigatingEventArgs e)
    {
             if (e.Uri.AbsolutePath.Contains("/file/"))
                {
                      MyUrl = e.Uri.ToString();
                         // and here I tried different codes construstors, methods but I can not get the filename
                }
            if (e.Uri.Segments[e.Uri.Segments.Length - 1].EndsWith(".exe"))
                {
                       // if the address ended with the FileName this code works well
                       Uri u = new Uri(e.Uri.ToString());
                      string filename = Path.GetFileName(ut.LocalPath);
                       MessageBox.Show(fileName);
                }
     }

回答1:


It doesn't have a "file name", unless there's a Content-Disposition header, including a filename-parm. It might resemble:

Content-Disposition: attachment; filename=FileA.abc

In that case, the file name would be FileA.abc.


I've not really worked with the WebClient class, however, and I don't see any easy way to access the headers. You'd have to switch to using HttpWebRequest, and do more work yourself.




回答2:


Content-Disposition should be as

Content-Disposition: attachment; filename=\"abc.msi\""

in here you want to get abc.msi. for that you can use following code.

            string contentDisposition = resp.Headers["Content-Disposition"];
            string fileName = string.Empty;
            if (!string.IsNullOrEmpty(contentDisposition))
            {
                string lookFor = "filename=";
                int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);
                if (index >= 0)
                    fileName = contentDisposition.Substring(index + lookFor.Length).Replace("\"", ""); ;
            } 


来源:https://stackoverflow.com/questions/7293944/how-get-file-name-from-url-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!