John Demetriou John Demetriou - 1 month ago 21
C# Question

Converting absolute path to relative path C#


Possible Duplicate:

Getting path relative to the current working directory?




I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.

For example the path in my code (and in my laptop for the image) is

C:/something/res/images/image1.jpeg


and I want the path in my code to be

..../images/image1.jpeg


So it can run wherever the folder is put, whatever the name of the
C:
partition is etc.

I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.

I have this code:

try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}


This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?

Answer

Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".

To get a better feel for this, try out the following as a test:

1) create a new visual studio sample project,

2) create an images folder at the same level as the .csproj

3) put some files in the images folder

4) put this sample code in your main method -

    static void Main(string[] args)
    {
        Console.WriteLine(Directory.GetCurrentDirectory());
        foreach (string s in Directory.EnumerateFiles("../../images/"))
        {
            Console.WriteLine(s); 
        }
        Console.ReadLine(); // Just to keep the console from disappearing.
    }

You should see the relative paths of all the files you placed in step (3).