[英]How Get File Name from URL ,C#/.NET?
如果地址以類似這樣的結尾,我如何獲得文件名。
/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);
}
}
除非有Content-Disposition標頭,包括文件名-參數,否則它沒有“文件名”。 它可能類似於:
Content-Disposition: attachment; filename=FileA.abc
在這種情況下,文件名將為FileA.abc
。
但是,我還沒有真正使用WebClient類,也沒有看到任何簡單的方法來訪問標頭。 您必須切換到使用HttpWebRequest ,然后自己做更多的工作。
內容處置應為
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("\"", ""); ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.