runtime icon indicating copy to clipboard operation
runtime copied to clipboard

DirectoryInfo.CreateSubdirectory(path) trims whitespace and returns parent directory

Open ianhays opened this issue 11 years ago • 2 comments

Calling directory.CreateSubdirectory("whitespaces") will return "directory" and create no subdirectory.

DirectoryInfo parentDir = new DirectoryInfo(TestDirectory);
DirectoryInfo childDir = parentDir.CreateSubdirectory("   ");
Assert.Equal(parentDir.FullName + Path.DirectorySeparatorChar, childDir.FullName);

If newlines or tabs are used, then it throws as expected:

DirectoryInfo parentDir = new DirectoryInfo(TestDirectory);
Assert.Throws<ArgumentException>(() => parentDir.CreateSubdirectory("\n"));
Assert.Throws<ArgumentException>(() => parentDir.CreateSubdirectory("\t"));

The reason for this is that dir.CreateSubdirectory(path) essentially wraps around Directory.CreateDirectory(Path.Combine(dir.FullName, path)) which trims trailing whitespace (in this case "path").

Is this functionality desired? It makes sense to keep curtailing trailing whitespace in Directory.CreateDirectory for back compat reasons, but having CreateSubdirectory on whitespace return the parent directory is unintuitive.

ianhays avatar Jul 17 '15 17:07 ianhays

That looks to me like a bug (one that exists on the desktop as well). @ericstj?

stephentoub avatar Jul 17 '15 17:07 stephentoub

It's been decided by popular vote to leave it this way and treat CreateSubDirectory as a caller to CreateDirectory. From this perspective, directory.CreateSubdirectory(dirName); should be treated as being equivalent to Directory.CreateDirectory(Path.Combine(directory.FullPath, dirName)); with regards to error checking. I added tests for either of the cases expressed in the original post.

ianhays avatar Aug 11 '15 20:08 ianhays