我正在运行一个非常简单的程序,它试图列出同一台机器上文件夹中的文件,该文件夹使用 UNC 格式指定(如 http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx 中所述):
static string rootDir = @"\\?\d:\share\input";<p></p>
static void Main(string[] args)
{
char[] invlidChars = Path.GetInvalidPathChars();
foreach (char invChar in invlidChars)
{
if (rootDir.Contains(invChar.ToString()))
{
Console.WriteLine("InvChar - {0}", invChar);
}
}
string[] matchFiles = Directory.GetFiles(rootDir);
}
但是 Directory.GetFiles() 不起作用并抛出一个 ArgumentException(当 - path 是零长度字符串、仅包含空格或包含一个或多个由 InvalidPathChars 定义的无效字符时抛出.)。 Console.Writeline() 不打印任何内容,这确认路径中没有无效字符。我在使用时遇到同样的异常 "\\UNC\?\d:\share\input"或 "\\UNC\?\machinename\share\input"或 “\\?\机器名\共享\输入”。
“d:\share\input”确实是一个共享文件夹。
有谁知道哪里出了问题?
谢谢!
最佳答案
问题是 \\?\
是 .NET 不支持的 Windows API 约定。如果您在链接中仔细阅读 \\?\
并不表示 UNC 路径,而是 Windows API 的特殊约定:
For file I/O, the "
\\?\
" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system.
.NET 兼容的 UNC 格式为 \\machinename\d$\share\input
。参见 this回答更多信息。
.NET 不支持它的原因很可能是扩展路径约定并非在所有平台上都可用,因此不能保证框架可以正常工作。
关于c# - UNC 路径不适用于 .NET?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11009013/