I am writing an application that needs to create a lot of folders. I ran into this stubborn error that I couldn't understand. I was getting DirectoryNotFoundException, which states in the exception message the exact string path that failed. I could copy paste that path into a file explorer bar and it would take me right there. My visual studio solution would fail at a line like this every time. I copy pasted the text into linqpad to isolate it and figure out what it didn't like. The exact same code works without issue in linqpad. I became very confused. I went down the rabbit hole for a while until I realized it was just the space at the end of a folder that it didn't like. Problem solved and lesson learned. I have now added that to some path sanitation functions I have.
What I don't get is why it works in Linqpad, but not VS. Linqpad 5 uses Roslyn and it works there. Linqpad 4 uses CSharpCodeProvider and it works there. Visual Studio uses CSC.exe and it does not work there. I have no idea how these vary.
Can anyone help me understand why they differ in this case? I'd like to know when I should take tests in Linqpad with a grain of salt(maybe always?).
The code below fails at CreateDirectory when running in Visual Studio. It succeeds when run in LinqPad 4 or 5. Code in question:
try
{
string myDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Directory.CreateDirectory(Path.Combine(myDocsPath, "SpaceOnTheEnd ", "NoSpaceOnTheEnd"));
Console.WriteLine("Creation succeeded.");
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException)
{
Console.WriteLine("Creation failed due to space.");
}
throw;
}