从C#中的URI字符串获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1105593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:22:43  来源:igfitidea点击:

Get file name from URI string in C#

c#stringurifilenames

提问by paulwhit

I have this method for grabbing the file name from a string URI. What can I do to make it more robust?

我有这种从字符串 URI 中获取文件名的方法。我该怎么做才能让它更健壮?

private string GetFileName(string hrefLink)
{
    string[] parts = hrefLink.Split('/');
    string fileName = "";

    if (parts.Length > 0)
        fileName = parts[parts.Length - 1];
    else
        fileName = hrefLink;

    return fileName;
}

采纳答案by Reed Copsey

You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPathto extract the filename.

您可以创建一个 System.Uri 对象,然后使用 IsFile 来验证它是一个文件,然后使用Uri.LocalPath来提取文件名。

This is much safer, as it provides you a means to check the validity of the URI as well.

这更安全,因为它也为您提供了一种检查 URI 有效性的方法。



Edit in response to comment:

编辑以回应评论:

To get just the full filename, I'd use:

要获得完整的文件名,我会使用:

Uri uri = new Uri(hreflink);
if (uri.IsFile) {
    string filename = System.IO.Path.GetFileName(uri.LocalPath);
}

This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.

这会为您完成所有错误检查,并且与平台无关。所有特殊情况都可以快速轻松地为您处理。

回答by Mike Hofer

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(hrefLink.Replace("/", "\"));
}

THis assumes, of course, that you've parsed out the file name.

当然,这假设您已经解析出文件名。

EDIT #2:

编辑#2:

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\"));
}

This should handle spaces and the like in the file name.

这应该处理文件名中的空格等。

回答by Le Zhang

Uri.IsFile doesn't work with http urls. It only works for "file://". From MSDN: "The IsFile property is truewhen the Scheme property equals UriSchemeFile." So you can't depend on that.

Uri.IsFile 不适用于 http 网址。它仅适用于“file://”。来自MSDN:“当 Scheme 属性等于 UriSchemeFile 时,IsFile 属性为。” 所以你不能依赖它。

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);

回答by Kostub Deshmukh

The accepted answer is problematic for http urls. Moreover Uri.LocalPathdoes Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath

接受的答案对于 http url 是有问题的。此外Uri.LocalPath,特定于 Windows 的转换,正如有人指出的那样,在那里留下查询字符串。更好的方法是使用Uri.AbsolutePath

The correct way to do this for http urls is:

对 http url 执行此操作的正确方法是:

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);

回答by Ronnie Overby

Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).

大多数其他答案要么不完整,要么不处理路径之后的内容(查询字符串/哈希)。

readonly static Uri SomeBaseUri = new Uri("http://canbeanything");

static string GetFileNameFromUrl(string url)
{
    Uri uri;
    if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
        uri = new Uri(SomeBaseUri, url);

    return Path.GetFileName(uri.LocalPath);
}

Test results:

检测结果:

GetFileNameFromUrl("");                                         // ""
GetFileNameFromUrl("test");                                     // "test"
GetFileNameFromUrl("test.xml");                                 // "test.xml"
GetFileNameFromUrl("/test.xml");                                // "test.xml"
GetFileNameFromUrl("/test.xml?q=1");                            // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3");                        // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3");                         // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3");        // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d");                 // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/");              // ""

回答by Zeus82

I think this will do what you need:

我认为这将满足您的需求:

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();

回答by Ali Yousefi

this is my sample you can use:

这是我可以使用的示例:

        public static string GetFileNameValidChar(string fileName)
    {
        foreach (var item in System.IO.Path.GetInvalidFileNameChars())
        {
            fileName = fileName.Replace(item.ToString(), "");
        }
        return fileName;
    }

    public static string GetFileNameFromUrl(string url)
    {
        string fileName = "";
        if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
        {
            fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
        }
        string ext = "";
        if (!string.IsNullOrEmpty(fileName))
        {
            ext = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(ext))
                ext = ".html";
            else
                ext = "";
            return GetFileNameValidChar(fileName + ext);

        }

        fileName = Path.GetFileName(url);
        if (string.IsNullOrEmpty(fileName))
        {
            fileName = "noName";
        }
        ext = Path.GetExtension(fileName);
        if (string.IsNullOrEmpty(ext))
            ext = ".html";
        else
            ext = "";
        fileName = fileName + ext;
        if (!fileName.StartsWith("?"))
            fileName = fileName.Split('?').FirstOrDefault();
        fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
        return GetFileNameValidChar(fileName);
    }

Usage:

用法:

var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");

回答by Gregory

Simple and straight forward:

简单直接:

            Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
            fileName = Path.GetFileName(uri.LocalPath);