Search code examples
c#file-exists

How to detect if a file exist in a project folder?


I am having a collection of images in my project folder.

how to detect if a image exist in my project folder? I am using c#. Thanks.


Solution

  • if (System.IO.File.Exists("pathtofile"))
      //it exist
    else
      //it does not exist
    

    EDITED MY ANSWER AFTER THE COMMENT OF THE QUESTION:

    I copied the code and changed the exits function, this should work

    string type = Path.GetExtension(filepath); 
    string path = @"image/" + type + ".png"; 
    //if(System.IO.File.Exists(path)) I forgot to use the full path
    if (System.IO.File.Exists(Path.Combine(Directory.GetCurrentDirectory(), path)))
     { return path; } 
    else 
     { return @"image/other.png"; }
    

    This will indeed work when your app is deployed