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

发布于 2024-07-26 18:44:57 字数 322 浏览 5 评论 0原文

我有这个方法可以从字符串 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;
}

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

情深如许 2024-08-02 18:44:57

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

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


编辑回应评论:

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

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

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

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

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


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.

鹿港小镇 2024-08-02 18:44:57

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

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

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

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
转身泪倾城 2024-08-02 18:44:57

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

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

检测结果:

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/");              // ""

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/");              // ""
dawn曙光 2024-08-02 18:44:57

接受的答案对于 http url 来说是有问题的。 此外Uri.LocalPath 进行 Windows 特定的转换,并且正如有人指出的那样,将查询字符串留在其中。 更好的方法是使用 Uri.AbsolutePath< /code>

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

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

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

The correct way to do this for http urls is:

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
臻嫒无言 2024-08-02 18:44:57

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

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

I think this will do what you need:

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
抱猫软卧 2024-08-02 18:44:57
using System.IO;

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

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

编辑#2:

using System.IO;

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

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

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:

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.

懒的傷心 2024-08-02 18:44:57

截至 2020 年,处理查询字符串和 编码的 URL

public static string GetFileNameFromUrl (string url)
{
    var decoded = HttpUtility.UrlDecode(url);

    if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
    {
        decoded = decoded.Substring(0, queryIndex);
    }

    return Path.GetFileName(decoded);
}

As of 2020, handles query strings & encoded URLs

public static string GetFileNameFromUrl (string url)
{
    var decoded = HttpUtility.UrlDecode(url);

    if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
    {
        decoded = decoded.Substring(0, queryIndex);
    }

    return Path.GetFileName(decoded);
}
黎歌 2024-08-02 18:44:57

这是我的示例,您可以使用:

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

用法:

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

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");
捂风挽笑 2024-08-02 18:44:57

简单直接:

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

Simple and straight forward:

            Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
            fileName = Path.GetFileName(uri.LocalPath);
浅黛梨妆こ 2024-08-02 18:44:57
  //First Method to get fileName from fileurl  


 List<string> fileNameListValues = new List<string>();  

//fileNameListValues List  consist of fileName and fileUrl 
//we need to get fileName and fileurl from fileNameListValues List 
 name 

 foreach(var items in fileNameListValues)
 {
var fileUrl = items;
var uriPath = new Uri(items).LocalPath;
var fileName = Path.GetFileName(uriPath);
 }


  //Second Way to get filename from fileurl is ->      


 fileNameValue = "https://projectname.com/assets\UploadDocuments\documentFile_637897408013343662.jpg";
 fileName = " documentFile_637897408013343662.jpg";

 //way to get filename from fileurl 

 string filename = 
  fileNameValue.Substring(fileNameValue.LastIndexOf("\\") + 1);
  //First Method to get fileName from fileurl  


 List<string> fileNameListValues = new List<string>();  

//fileNameListValues List  consist of fileName and fileUrl 
//we need to get fileName and fileurl from fileNameListValues List 
 name 

 foreach(var items in fileNameListValues)
 {
var fileUrl = items;
var uriPath = new Uri(items).LocalPath;
var fileName = Path.GetFileName(uriPath);
 }


  //Second Way to get filename from fileurl is ->      


 fileNameValue = "https://projectname.com/assets\UploadDocuments\documentFile_637897408013343662.jpg";
 fileName = " documentFile_637897408013343662.jpg";

 //way to get filename from fileurl 

 string filename = 
  fileNameValue.Substring(fileNameValue.LastIndexOf("\\") + 1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文