鉴于以下控制台应用程序,我在理解.net Framework行为时遇到了问题。
我确实有一个文件夹(Windows)的绝对路径,我想创建它。为了避免在Directory.CreateDirectory()
期间出现 PathTooLongException ,我通过为路径执行Path.GetFullPath()
来提前检查。但是,这不是我不明白的原因。
我的问题是:
注意: - 简单地在创建期间捕获异常对我来说不是一个解决方案,因为真实世界的应用程序在不同的地方进行PathTooLong检查和实际创建,其中很多其他路径相关的东西发生在它们之间。因此,检查它只是迟到。
编辑: 我检查Path.GetFullPath()
不修改路径,但为了简洁起见,在我的示例中将其保留了下来。
这是我的示例代码:
using System;
using System.IO;
namespace PathTooLongExperiments
{
class Program
{
static void Main(string[] args)
{
string pathThatFailsCreate = @"C:\Users\qs\1234567\vkT7eYDrFL0lZzEVBwx3O-8GE632bW64IvUiCqjOHv00661Kh,lVminnGrM4Y82EKD6\qozVNx8NoSDOhGoTV1f4syjtciBfv0fLCN7iSaRBuiHtIfgHNGJDbKQ28G4uqIumKa-\DtfhThPUI7J4hGxkPUem11PZBofq1uqn-7xw9YjBODLRouNCKo7T7-ODTc,Qjed01R0\8GfPtnmuUANti7sN55aq27cW";
TryCreateFolder(pathThatFailsCreate);
string pathThatWorks = @"C:\Users\qs\1234567\vkT7eYDrFL0lZzEVBwx3O-8GE632bW64IvUiCqjOHv00661Kh,lVminnGrM4Y82EKD6\qozVNx8NoSDOhGoTV1f4syjtciBfv0fLCN7iSaRBuiHtIfgHNGJDbKQ28G4uqIumKa-\DtfhThPUI7J4hGxkPUem11PZBofq1uqn-7xw9YjBODLRouNCKo7T7-ODTc,Qjed01R0\8GfPtnmuUANti7sN55aq27c";
TryCreateFolder(pathThatWorks);
Console.WriteLine("Done. Press any key");
Console.ReadKey();
}
private static void TryCreateFolder(string path)
{
Console.WriteLine($"Attempting to create folder for path: {path}");
string checkedPath;
try
{
checkedPath = Path.GetFullPath(path);
}
catch (PathTooLongException)
{
Console.WriteLine("PathToLong check failed!");
Console.WriteLine($"Path length: {path.Length}");
Console.WriteLine($"Path: {path}");
Console.ReadKey();
return;
}
try
{
Directory.CreateDirectory(checkedPath);
}
catch (PathTooLongException)
{
// Why is this possible? We've checked for path too long by Path.GetFullPath, didn't we?
Console.WriteLine("Could not create directory because the path was to long");
}
}
}
}