在C#/ .NET中结合path和文件名的最佳方法是什么?
将path与文件名结合的最佳方法是什么?
也就是说,给定c:\foo和bar.txt ,我想要c:\foo\bar.txt 。 
 给定c:\foo和..\bar.txt ,我想要一个错误或c:\foo\bar.txt (所以我不能直接使用Path.Combine() )。 同样,对于c:\foo和bar/baz.txt ,我想要一个错误或c:\foo\baz.txt (而不是c:\foo\bar\baz.txt )。 
我意识到,我可以检查文件名不包含“\”或“/”,但是这足够吗? 如果不是,那么正确的支票是什么?
如果你想“坏”文件名产生一个错误:
 if (Path.GetFileName(fileName) != fileName) { throw new Exception("'fileName' is invalid!"); } string combined = Path.Combine(dir, fileName); 
或者,如果您只是想默默纠正“坏”文件名而不抛出exception:
 string combined = Path.Combine(dir, Path.GetFileName(fileName)); 
你可以使用:
 Path.Combine(folder, Path.GetFileName(fileName)) 
或者,跳过\(未testing,也许Path.GetFileName自动处理这个)
 Path.Combine(folder, Path.GetFileName(fileName.Replace("/","\\"))) 
 请注意,当您使用Path.Combine(arg1, arg2) – 如果您的用户为arg2input完全限定的文件path,它将忽略arg1,并使用arg2作为path。 
 在我看来,微软搞砸了! 这可以让用户窃听整个文件系统。 被警告,请仔细阅读! 如果你正在合并path使用: var newPath = path1 + @"\" + path2; 更简单,没有意外的结果…