【问题标题】:How Get File Name from URL ,C#/.NET?如何从 URL、C#/.NET 获取文件名?
【发布时间】:2011-09-03 15:14:08
【问题描述】:

如果地址以这样的结尾,我如何获取文件名。
/download/file/36fdd4aebda3819d329640ce75755657bc0c0d4c6811432b3bb6aac321dc78d/ ?

这是简化的代码示例,

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);
                }
     }

【问题讨论】:

    标签: c# download webclient filenames file-type


    【解决方案1】:

    它没有“文件名”,除非有 Content-Disposition 标头,包括文件名参数。它可能类似于:

    Content-Disposition: attachment; filename=FileA.abc
    

    在这种情况下,文件名将是FileA.abc


    但是,我并没有真正使用过WebClient 类,而且我没有看到任何简单的方法来访问标题。你必须改用HttpWebRequest,自己做更多的工作。

    【讨论】:

      【解决方案2】:

      Content-Disposition 应该是

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

      在这里你想得到 abc.msi。为此,您可以使用以下代码。

                  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("\"", ""); ;
                  } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        • 2017-11-17
        • 2021-06-20
        • 1970-01-01
        相关资源
        最近更新 更多