在C#/.NET中结合路径和文件名的最佳方法是什么?

问题描述:

将路径与文件名结合在一起的最佳方法是什么?

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

也就是说,给定c:\foobar.txt,我想要c:\foo\bar.txt.

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

给出c:\foo..\bar.txt,我想要一个错误或c:\foo\bar.txt(所以我不能直接使用Path.Combine()).同样,对于c:\foobar/baz.txt,我想要一个错误或c:\foo\baz.txt(不是c:\foo\bar\baz.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?

如果您想让错误的"文件名生成错误:

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));