What is the best way to combine a path and a filename in C#/.NET?

Rasmus Faber picture Rasmus Faber · Jun 26, 2009 · Viewed 80.6k times · Source

What is the best way to combine a path with a filename?

That is, given c:\foo and bar.txt, I want c:\foo\bar.txt.

Given c:\foo and ..\bar.txt, I want either an error or c:\foo\bar.txt (so I cannot use Path.Combine() directly). Similarly for c:\foo and bar/baz.txt, I want an error or c:\foo\baz.txt (not c:\foo\bar\baz.txt).

I realize, I could check that the filename does not contain '\' or '/', but is that enough? If not, what is the correct check?

Answer

LukeH picture LukeH · Jun 26, 2009

If you want "bad" filenames to generate an error:

if (Path.GetFileName(fileName) != fileName)
{
    throw new Exception("'fileName' is invalid!");
}
string combined = Path.Combine(dir, fileName);

Or, if you just want to silently correct "bad" filenames without throwing an exception:

string combined = Path.Combine(dir, Path.GetFileName(fileName));