locked
How can i check if a file exists ion a directory ? RRS feed

  • Question

  • User1253338400 posted

    Hi 

    I do the following currently.

    if (Directory.Exists(c:\\test))
    {
       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 ?

    Tuesday, June 30, 2020 6:47 AM

Answers

  • User-821857111 posted

    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.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 30, 2020 7:01 AM

All replies

  • User-821857111 posted

    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.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 30, 2020 7:01 AM
  • User288213138 posted

    Hi robby32,

    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.

    if (File.Exists(@"c:\\test\myfile.txt"))

    Best regards,

    Sam

    Tuesday, June 30, 2020 10:27 AM
  • User303363814 posted

    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. 

    Tuesday, June 30, 2020 11:49 PM