有谁知道任何一个好的库,以一种很好的方式来抽象路径操作的问题吗?我希望能够用任意分隔符(例如'/'或':')组合和分析路径,而不用重新发明轮子。.NET路径操作库
这是一个耻辱,System.IO.Path
是不是更可重复使用。
感谢
有谁知道任何一个好的库,以一种很好的方式来抽象路径操作的问题吗?我希望能够用任意分隔符(例如'/'或':')组合和分析路径,而不用重新发明轮子。.NET路径操作库
这是一个耻辱,System.IO.Path
是不是更可重复使用。
感谢
System.IO.Path.Combine将工作非常适合许多不同类型的路径:
http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx
System.IO.Path.Combine使用当前平台的标准分离器结合路径。这意味着在Windows上使用“\”,而在unix/linux(mono)上使用“/”。你能否给出一些你想要结合什么路径的样本,以及在什么平台上?
由于它使用和理解的分隔符是预定义的,因此System.IO.Path无法帮助。正如我所说的,我需要使用任意的分隔符,如':'和'/'。我可以用System.IO.Path做的最好的事情是将我的任意字符转换为可识别的字符(比如'\'),然后再转换回来。但这是一个很好的解决方案。 – 2009-08-23 14:50:42
您正在描述正则表达式!用它作为你需要做的事情的基础。
检查帕特里克库来处理路径操作link text
我不能告诉你可能会使用基于什么样的环境了你的分隔,但我从来没有见过这样的库之前。
因此,使用反射器和System.IO.Path
作为基础不难重新发明轮子。
InvalidPathChars
。这几乎是框架使用的代码,所以它应该是一样快或者只有微不足道的差别。可能会或可能不会比RegEx更快,但它可能值得一试。
class ArbitraryPath
{
private readonly char _directorySeparatorChar;
private readonly char _altDirectorySeparatorChar;
private readonly char _volumeSeparatorChar;
public ArbitraryPath(char directorySeparatorChar, char altDirectorySeparatorChar, char volumeSeparatorChar)
{
_directorySeparatorChar = directorySeparatorChar;
_altDirectorySeparatorChar = altDirectorySeparatorChar;
_volumeSeparatorChar = volumeSeparatorChar;
}
public string Combine(string path1, string path2)
{
if ((path1 == null) || (path2 == null))
{
throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
}
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
if (path2.Length == 0)
{
return path1;
}
if (path1.Length == 0)
{
return path2;
}
if (IsPathRooted(path2))
{
return path2;
}
char ch = path1[path1.Length - 1];
if (ch != _directorySeparatorChar && ch != _altDirectorySeparatorChar && ch != _volumeSeparatorChar)
{
return (path1 + _directorySeparatorChar + path2);
}
return (path1 + path2);
}
public bool IsPathRooted(string path)
{
if (path != null)
{
CheckInvalidPathChars(path);
int length = path.Length;
if (length >= 1 && (path[0] == _directorySeparatorChar || path[0] == _altDirectorySeparatorChar) || length >= 2 && path[1] == _volumeSeparatorChar)
{
return true;
}
}
return false;
}
internal static void CheckInvalidPathChars(string path)
{
for (int i = 0; i < path.Length; i++)
{
int num2 = path[i];
if (num2 == 0x22 || num2 == 60 || num2 == 0x3e || num2 == 0x7c || num2 < 0x20)
{
throw new ArgumentException("Argument_InvalidPathChars");
}
}
}
}
恐怕you'll have to implement a path class yourself,就像我一样。它提供了以下优点:
我认为System.IO.Path很好用。你有特定的任务,你需要它无法处理? – Espo 2008-09-09 14:53:45
@Espo:试着读我的问题的第二句话。 – 2009-08-23 14:51:30
您可以使用[Path.DirectorySeparatorChar](http://msdn.microsoft.com/zh-cn/library/system.io.path.directoryseparatorchar.aspx)? – 2008-09-09 14:57:53