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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1048129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:57:08  来源:igfitidea点击:

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

c#.netpathfilenames

提问by Rasmus Faber

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

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

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

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

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

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

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

采纳答案by LukeH

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

回答by GvS

You could use:

你可以使用:

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

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

或者,跳过 \ (未测试,也许 Path.GetFileName 会自动处理)

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

回答by Ravi

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.

请注意,当您使用Path.Combine(arg1, arg2)- 如果您的用户输入 arg2 的完全限定文件路径时,它将忽略 arg1,并使用 arg2 作为路径。

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...

在我看来,微软搞砸了!这可以让您对用户入侵整个文件系统保持开放。请注意,阅读细则!如果您正在组合路径,请使用:var newPath = path1 + @"\" + path2;更简单且没有意外结果...