Last post Jun 30, 2020 11:49 PM by PaulTheSmith
Jun 30, 2020 06:47 AM|robby32|LINK
I do the following currently.
if (File.Exists("c:\\test+ @"\myfile.txt"))
I do this in a number of places in my code , can i do these 2 if statements in one line ?
Jun 30, 2020 07:01 AM|Mikesdotnetting|LINK
If you are only checking if a file exists, there is no need to check if the directory exists as well. Either the file exists in the directory, or it doesn't. Obviously if the directory doesn't exist, the file won't exist either.
Jun 30, 2020 10:27 AM|samwu|LINK
As Mike said, if the directory does not exist, then this file certainly does not exist.
If you want to merge them into one line, then you can directly use File.Exists() method.
Jun 30, 2020 11:49 PM|PaulTheSmith|LINK
It's also useful to use Path.Combine to join one or more directories and a filename. You don't have to worry about leading/trailing separators. So if you code is actually
string appRoot = callToSomeConfigMethod();
string dataFolder = "data";
string filename = "myfile.txt";
Then your check would be better written as
File.Exists(Path.Compbine(appRoot, dataFolder, file));
you can have as many parameters to Path.Combine as you need and it doesn't matter if they start/end with the Path.DirectorySeparatorChar character - Path.Combine works it out.