|
I often need to work with filePaths, such as getting an absolute file name given a directory and a fileName. One way for developers to do this is simply string concatenation. A lot of devs do this because it appears so simple. But the problem is that when passing in the directory as a string, you often don't know if it will end with a final slash or not - i.e "C:\Temp" or "C:\Temp\". Merely doing string concat will screw it up, you could get a non-existent file like "C:\Temp\\MyFile.txt".
A much better approach is to use System.IO.Path.Combine. This allows you to have a directory (with or without the slash), and the combine method if smart enough to handle it:
public static string GetFileName(string strDir, string strName)
{
//return strDir + @"\" + strName; //BAD
return System.IO.Path.Combine(strDir, strName); //GOOD
}
What's funny is that both options are just 1 line of code and take essentially the exact same amount of time to write. However, the first is very brittle, and could likely cost you tons of time tracking down an error because someone passed in a directory with or without that extra slash. The second just works.
I am not having a lot of luck with this maybe you can elaborate further. I
always concatenate in this situation but make sure I cleanse the data going
in so I know where my slashes are, my simple tests on this actually show
this to be a pretty poor solution. So maybe you can clarify. Note my method
I use would cleans the dorectories passes in and coming out they would all
be the same.
string baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
string tempDirectory;
Console.WriteLine("Application Domain Base Directory");
Console.WriteLine(baseDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "/test");
Console.WriteLine(tempDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "\\test");
Console.WriteLine(tempDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "/test/");
Console.WriteLine(tempDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "/test\\");
Console.WriteLine(tempDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "test");
Console.WriteLine(tempDirectory);
tempDirectory = System.IO.Path.Combine(baseDirectory, "test\\");
Console.WriteLine(tempDirectory);
Hey Jeff, I'm not sure what the exact question is.
If you just want to combine two directories, I think it's just this (no
slashes needed)
tempDirectory = System.IO.Path.Combine(baseDirectory, "test");
I think Jeff's question is about a documented - but very annoying -
behavior of Path.Combine that I've run into before.
"If path2 includes a root, path2 is returned."