Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 228
Rasmus Faber Avatar asked Jun 26 '09 09:06

Rasmus Faber


People also ask

How do I separate the filename and path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

What is the difference between a path and a file name?

A file name is a name a particular inode is called inside a particular directory. A path is some instructions for how to reach an inode from a known point.

How check if file exists C#?

To check whether the specified file exists, use the File. Exists(path) method. It returns a boolean value indicating whether the file at the specified path exists or not.


1 Answers

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)); 
like image 174
LukeH Avatar answered Sep 21 '22 19:09

LukeH