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

标签 c# path types uri

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

我应该使用现有的 C# 类型吗? Uri type可能有效,但乍一看,它似乎只是 URI。

最佳答案

使用 Uri 类,它似乎可以工作。它将任何文件路径转换为 ​​Uri 中的“file:///...”语法。它按预期处理任何 URI,并且它有能力处理相对 URI。这取决于您尝试使用的其他内容那条路。

(已更新以显示相对 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());

给我这个输出:

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

关于c# 类型来处理相对和绝对 URI 和本地文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799367/

相关文章:

C# 相当于 AtlEscapeUrl

c# - DbContext 处理?

c - C 中的 Unix 路径解析

types - 记录判别式能否在 Ada 中间接确定数组长度?

c# - 对于特定属性,您如何在 ModelState 中获取错误?

c# - 使用 WebKit.NET 读取 header 中的链接

javascript - Paper.js 点和路径之间的距离

javascript - 如何定义 Node.js 应用上下文路径?

c - 使用空指针交换数组中的元素

python - 为什么 enumerate、zip、range 类型不属于 types.GeneratorType?