Given the below console application, I have a problem understanding the .net Framework behavior.
I do have an absolute path to a folder (Windows), that I want to create. To avoid a PathTooLongException during Directory.CreateDirectory()
I check for that in advance by doing a Path.GetFullPath()
for the path. However, this is not working for a reason I don't understand.
My questions are:
- Why is this happening?
- How can I (really, as in reliably) check if the path is to long before creating the directory
Notes: - Simply catching the Exception during creation is not a solution for me, because the real world application does the PathTooLong check and the actual createion this on different places where a lot of other path related stuff is happening in between. So it would simply be to late to check that.
Edit: I checked that Path.GetFullPath()
does not modify the path, but left that out in my example for brevity.
Here is my example code:
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");
}
}
}
}