簡體   English   中英

在 .NET 中將 URI 路徑轉換為相對文件系統路徑

[英]Converting a URI path to a relative file system path in .NET

如何在 .NET foo\\bar.txt絕對或相對 URI 路徑(例如/foo/bar.txt )轉換為(分段)對應的相對文件系統路徑(例如foo\\bar.txt )?

我的程序不是 ASP.NET 應用程序。

您是否已經嘗試過Server.MapPath
Uri.LocalPath屬性? 類似於以下內容:

string uriString = "file://server/filename.ext";
// Lesson learnt - always check for a valid URI
if(Uri.IsWellFormedUriString(uriString))
{
    Uri uri = new Uri(uriString);
    Console.WriteLine(uri.LocalPath);
}

我想出了這種從相對或絕對 URI 和基本路徑生成完整絕對文件系統路徑的方法。

和:

Uri basePathUri = new Uri(@"C:\abc\");

從相對 URI:

string filePath = new Uri(basePathUri, relativeUri).AbsolutePath;

從絕對URI:

// baseUri is a URI used to derive a relative URI
Uri relativeUri = baseUri.MakeRelativeUri(absoluteUri);
string filePath = new Uri(basePathUri, relativeUri).AbsolutePath;

你可以這樣做:

var localPath = Server.MapPath("/foo/bar.txt");

有關詳細信息,請參閱 MSDN

由於后端或框架更改,並非所有人都可以訪問 server.MapPath,並且有很多方法其中之一可能是這樣的

public enum FileLocation
{
    NotSet,
    Disk,
    Resource,
}

private static readonly string[] FileExtenstions = new[] {
    ".js"
    ,".ts"
    ,".vue"
    ,".css"
    ,".jpg"
    ,".png"
    ,".gif"
    ,".ico"
    ,".svg"
    ,".ttf"
    ,".eot"
    ,".ttf"
    ,".woff"
    ,".woff2"
    ,".mp4"
    ,".mp3"
    ,".emf"
};

public FileLocation IsMappedTo(Uri uri)
{
    if (uri is null)
    {
        throw new ArgumentNullException(nameof(uri));
    }
    //make sure we support .net default URI contract
    if (uri.IsFile)
        return FileLocation.Disk;

    //now assume you are looking in a web application
    var path = uri.AbsolutePath;
    if (path.Length == 0 || path.Equals("/",StringComparison.Ordinal) || path.Length< FileExtenstions.Min(s=>s.Length))
        return FileLocation.NotSet;

    //get the directory normally one would use IWebHostEnvironment.ContentRootPath different versions .net will have other methods
    var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");

    //get all resources names from the assembly hosting this class out side if the loop from this assembly you can also use
    //you can also use GetManifestResourceNames() to use the web application's assembly
    var resourceNames = new HashSet<string>(this.GetType().Assembly.GetManifestResourceNames());
    var entryAssembly = Assembly.GetEntryAssembly();
    if (entryAssembly != null && entryAssembly != this.GetType().Assembly)
    {
        foreach (var entry in entryAssembly.GetManifestResourceNames())
        {
            if (string.IsNullOrEmpty(entry))
                resourceNames.Add(entry);
        }
    }

    for (var i = 0; i < FileExtenstions.Length; i++)
    {
        if (FileExtenstions[i].Equals(path[FileExtenstions[i].Length..], StringComparison.OrdinalIgnoreCase) || path.Contains(FileExtenstions[i], StringComparison.OrdinalIgnoreCase))
        {
            //exists on disk
            if (File.Exists(Path.Combine(dir, path.Replace("/", @"\", StringComparison.Ordinal))))
                return FileLocation.Disk;

            //has a file as an embedded resource with the same name (ignores the path) so you might have duplicates names
            if (resourceNames.Any(a => a.EndsWith(path.Split('/')[^1], StringComparison.OrdinalIgnoreCase)))
                return FileLocation.Resource;
        }
    }

    return FileLocation.NotSet;
}

在此之后,您只需執行以下操作:

switch (IsMappedTo(url))
{
    case FileLocation.NotSet:
        break;

    case FileLocation.Disk:
        break;

    case FileLocation.Resource:

        break;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM