source

C#의 URI 문자열에서 파일 이름 가져오기

bestscript 2023. 8. 8. 23:26

C#의 URI 문자열에서 파일 이름 가져오기

문자열 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;
}

그냥 시스템을 만들 수 있습니다.URI 개체를 사용하고 IsFile을 사용하여 파일인지 확인한 다음 URI를 사용합니다.파일 이름을 추출할 LocalPath입니다.

URI의 유효성을 확인할 수 있는 수단도 제공하므로 훨씬 안전합니다.


주석에 대한 응답으로 편집:

전체 파일 이름만 가져오려면 다음을 사용합니다.

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

이렇게 하면 모든 오류를 확인할 수 있으며 플랫폼 중립적입니다.모든 특별한 사건은 빠르고 쉽게 처리됩니다.

Uri.IsFile이 http URL에서 작동하지 않습니다."file://"에만 작동합니다.MSDN: "Schem 속성이 UriSchemeFile과 같을 때 IsFile 속성은 true입니다."그래서 당신은 그것에 의존할 수 없습니다.

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

대부분의 다른 답변은 불완전하거나 경로 다음에 오는 항목(쿼리 문자열/해시)을 처리하지 않습니다.

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

허용된 답변은 http URL에 문제가 있습니다.또한 Windows에서는 특정 변환을 수행하며, 누군가가 지적한 대로 쿼리 문자열이 남아 있습니다.더 나은 방법은 사용하는 것입니다.

http URL에 대해 올바른 방법은 다음과 같습니다.

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

이렇게 하면 필요한 작업을 수행할 수 있을 것입니다.

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
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("/", "\\"));
}

이렇게 하면 파일 이름의 공백 등을 처리할 수 있습니다.

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

이것은 당신이 사용할 수 있는 나의 샘플입니다.

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

단순하고 간단한 기능:

            Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
            fileName = Path.GetFileName(uri.LocalPath);
  //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);

언급URL : https://stackoverflow.com/questions/1105593/get-file-name-from-uri-string-in-c-sharp