Checking the existence of a file using relative path

You just need to define what your file is relative to

  • Your application main assembly?
  • Current directory?
  • Application data directory?
  • name it...

In each of these cases I'd suggest you to convert it into an absolute path by Path.Combine method:

public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

...

//calling with a '/' heading makes the path absolute so I removed it
var fullPath = Path.Combine(AppRoot, "images/Customswipe_a.png");
var exists = File.Exists(fullPath);

This way you can guarantee where you are looking for. Even the Open/Save file dialogs may change your current directory. So, calling File.Exists without full path is usually a wrong decision.


I guess that you are running this code in asp.net application, thats why you get false.

In asp.net you should use Server.MapPath("/images/Customswipe_a.png") to get "correct" path (relative to the web application root directory). Otherwise you get path local to the webserver executable (IIS/WEBDAV/..name any other).


The relative path is relative to the current working directory. It may not be the application directory. Call GetCurrentDirectory() to check the actual path you are testing.


That's not a relative path. You need to leave off the first / otherwise it will be interpreted as being rooted (i.e. C:/images...)

Tags:

C#