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

What is the best way to combine a path with a file name?

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 understand, I could check that the file name does not contain '\' or '/', but is that enough? If not, what is the correct check?

+47
c # filenames path
Jun 26 '09 at 9:09
source share
3 answers

If you want the "bad" file names 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 quietly fix the "bad" file names without throwing an exception:

 string combined = Path.Combine(dir, Path.GetFileName(fileName)); 
+78
Jun 26 '09 at 9:18
source share

You can use:

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

or to skip \ (not tested, perhaps Path.GetFileName handles this automatically)

 Path.Combine(folder, Path.GetFileName(fileName.Replace("/","\\"))) 
+16
Jun 26 '09 at 9:13
source share

Remember that when you use Path.Combine(arg1, arg2) - if your user enters a fully qualified file path for arg2, he ignores arg1 and uses arg2 as the path.

In my opinion, Microsoft squinted! This can leave you wide open when a user hacks your entire file system. Be careful, read the fine print! If you combine paths, use: var newPath = path1 + @"\" + path2; simpler and without unexpected results ...

+1
Jun 02 '15 at 19:08
source share



All Articles