Converting a URI path to a relative file system pa

2020-02-26 02:35发布

How do I convert an absolute or relative URI path (e.g. /foo/bar.txt) to a (segmentwise) corresponding relative file system path (e.g. foo\bar.txt) in .NET?

My program is not an ASP.NET application.

标签: c# .net path uri
3条回答
该账号已被封号
2楼-- · 2020-02-26 03:04

Have you already tried Server.MapPath?
or Uri.LocalPath property? Something like following :

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);
}
查看更多
我想做一个坏孩纸
3楼-- · 2020-02-26 03:14

You can do this:

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

See MSDN for details

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-26 03:28

I figured out this way to produce a full absolute file system path from a relative or absolute URI and a base path.

With:

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

From a relative URI:

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

From an absolute URI:

// baseUri is a URI used to derive a relative URI
Uri relativeUri = baseUri.MakeRelativeUri(absoluteUri);
string filePath = new Uri(basePathUri, relativeUri).AbsolutePath;
查看更多
登录 后发表回答