Reputation: 1715
In my programs I frequently have file names and/or paths that are configured in my app.config file. This will usually be something like:
<add key="LogFileDirectory" value="C:\Logs" />
<add key="SaveLogFileTo" value="MyLogFile.txt" />
In my actual application code, I'll frequently concatenate these together with code similar to this:
var logFile = ConfigurationManager.AppSettings["LogFileDirectory"]
+ @"\" +
ConfigurationManager.AppSettings["SaveLogFileTo"];
Now, the result of the above code would give a log file path of C:\Logs\MyLogFile.txt
, however, if the end-user specifies the log file directory in the configuration file as C:\Logs\
with a trailing backslash, my code results in an actual path of C:\Logs\\MyLogFile.txt
with a double backslash between the directory and the file.
In my experience, this works just fine in practice. As a matter of fact, even dropping to a command prompt and executing cd c:\\\\\\windows\\\
works in practice.
My question is, what, if any, are the consequences of having paths like this? I don't want to be using this "feature" in production code if it is something that is undocumented and subject to be broken at some point in the future with a new release of Windows.
Upvotes: 3
Views: 2476
Reputation: 69
At least these kind of consequences there are:
del command cannot delete the file if you provide two backslashes after the drive letter and colon:
C:\>del c:\\foo.txt
The filename, directory name, or volume label syntax is incorrect.
C:\>del c:\\bar\foo.txt
The network path was not found.
I mean, according to my experiments, the cmd.exe built in "del" command has a bug that tries to access a network share instead.
The bug is dangerous actually. The del command believes that c:\\bar\foo\zap.txt
means \\bar\foo\zap.txt
and if there really is a server "bar" that has share "foo" that has file "zap.txt", an incorrect file will be deleted if you meant a local file c:\bar\foo\zap.txt
instead.
I do not know that other commands would behave this way. For example the built in type and copy commands ignore the duplicate backslash and refer to local file.
Upvotes: 0
Reputation: 103467
There are no consequences that I know of, and it's not likely to be broken in future versions, because a lot of people will be doing the same as you.
However, the correct way to combine paths in C# is to use Path.Combine
, which will remove any extra backslashes for you:
var logFile = Path.Combine(
ConfigurationManager.AppSettings["LogFileDirectory"],
ConfigurationManager.AppSettings["SaveLogFileTo"]);
Upvotes: 3