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

组合路径和文件名的最佳方式是什么?

也就是说,给定 c:\foobar.txt,我要 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)。

我意识到,我可以检查文件名不包含’或’/’,但这足够了吗?如果没有,正确的检查是什么?

99488 次浏览

You could use:

Path.Combine(folder, Path.GetFileName(fileName))

or, to skip out the \ (not tested, maybe the Path.GetFileName handles this automatically)

Path.Combine(folder, Path.GetFileName(fileName.Replace("/","\\")))

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

Be aware that when you use Path.Combine(arg1, arg2) - if your user inputs a fully-qualified file path for arg2 it will disregard arg1, and use arg2 as the path.

In my opinion, Microsoft screwed up there! This can leave you wide open with the user hacking your entire filesystem. Be warned, read the fine print! If you're combining paths use: var newPath = path1 + @"\" + path2; simpler and no unexpected results...