Extra slashes in path variable of File.Copy() or Directory.CreateDirectory() methods
When I use some System.IO
methods, and "accidentally" put extra slashes (\
) in the path variables, nothing special seems to happen. No errors or warnings, and the code works as if just the right amount of slashes were present.
Example:
Directory.CreateDirectory(@"C:\Users\Public\Documents\\test");
File.Copy(@"C:\Users\Public\\Documents\test.txt", @"C:\开发者_如何学运维Users\\Public\Documents\test\test.txt", true);
So I'm wondering, is it potentially dangerous if the code above had extra slashes sometimes, or would it not matter one iota under any circumstances?
Windows is quite resilient to this, haven't noticed a problem yet.
Take a look at the snippet in this thread. Note the value of the _ACP_INCLUDE environment variable. You have to scroll to the right to see:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\\include;
Afaik, a lot of machines that have VS2008 have this bad path, mine certainly does. Nevertheless, it certainly can trip up your own code when you parse path strings.
Windows does not seem to mind, but why not make elegant code?
I'm pretty sure Windows "normalizes" the path structure before using it. To be safe, however, it is best to combine paths using:
Path.Combine(string1, string2);
instead of concatenating two strings.
The case you should know,
CreateFileW(L"D:\\1\\test.txt", GENERIC_READ, 0, 0, CREATE_NEW, 0, 0);
// A file has been created.
CreateFileW(L"D:\\1\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
// Of course, the file will be opened well.
CreateFileW(L"D:\\1\\\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
// It works well too. Windows subsystem does canonicalize that.
CreateFileW(L"\\\\?\\D:\\1\\\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
// '\\?\' prefix tell Windows "Don't touch my path, just send it to filesystem"
// So it will be failed.
http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
I have no idea how .NET wraps this api. I guess Hans Passant might knows well about this. :)
精彩评论