c# 类型来处理相对和绝对 URI 以及本地文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/799367/
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-05 01:39:15  来源:igfitidea点击:

c# type to handle relative and absolute URI's and local file paths

c#pathtypesuri

提问by BCS

I have a use cases where I will be dealing with both local file paths (e.g. c:\foo\bar.txt) and URI's (e.g. http://somehost.com/fiz/baz). I also will be dealing with both relative and absolute paths so I need functionality like Path.Combineand friends.

我有一个用例,我将同时处理本地文件路径(例如c:\foo\bar.txt)和 URI(例如http://somehost.com/fiz/baz)。我还将处理相对路径和绝对路径,因此我需要像Path.Combine和朋友一样的功能。

Is there an existing C# type I should use?The Uri typemight work but at a passing glance, it seems to be URI only.

我应该使用现有的 C# 类型吗?URI类型可能会奏效,但在路过一目了然,它似乎只是URI。

采纳答案by Erich Mirabal

Using the Uri class, it seems to be working. It turns any file path to the `file:///..." syntax in the Uri. It handles any URI as expected, and it has capacity to deal with relative URIs. It depends on what else you are trying to do with that path.

使用 Uri 类,它似乎有效。它将任何文件路径转换为 ​​Uri 中的 `file:///..." 语法。它按预期处理任何 URI,并且它具有处理相对 URI 的能力。这取决于您还想做什么那条路。

(Updated to show the use of relative Uri's):

(更新以显示相对 Uri 的使用):

string fileName = @"c:\temp\myfile.bmp";
string relativeFile = @".\woohoo\temp.bmp";
string addressName = @"http://www.google.com/blahblah.html";

Uri uriFile = new Uri(fileName);
Uri uriRelative = new Uri(uriFile, relativeFile);
Uri uriAddress = new Uri(addressName);

Console.WriteLine(uriFile.ToString());
Console.WriteLine(uriRelative.ToString());
Console.WriteLine(uriAddress.ToString());

Gives me this output:

给我这个输出:

file:///c:/temp/myfile.bmp  
file:///c:/temp/woohoo/temp.bmp  
http://www.google.com/blahblah.html