Home > C# > How to get relative path in C# (absolute)

How to get relative path in C# (absolute)

As I introduced in the past post “Cách lấy đường dẫn tương đối“, we can get the relative path in Java. But, I could not use this way for such a case in Csharp. So, I introduce a new way to make Csharp can find the specified files as the same way you used in Java. That means you just only enter the path to file like a relative path.
For instance, you have the directory as following:
You now want to get an image in folder Images, and your execution file is in Debug directory. In fact, this is get the absolute path to the file you want. You create a method as bellow:

public string getAbsoluteDir(string currentEXEFileDir, string relativeDir)
    string[] absDirs = currentEXEFileDir.Split('\\');
    string[] relDirs = relativeDir.Split('\\');

    int numberOfBack = 0;
    while(numberOfBack < relDirs.Length)
       if (!relDirs[numberOfBack].Equals(".."))
    string[] absDirs1=new string[absDirs.Length-numberOfBack];
    for (int i = 0; i < absDirs.Length-numberOfBack; i++)
        absDirs1[i] = absDirs[i];
    StringBuilder targetDirectory = new StringBuilder();
    foreach (string item in absDirs1)
        targetDirectory.Append(item + "\\");
    for (int i = numberOfBack ; i < relDirs.Length; i++)
        targetDirectory.Append(relDirs[i] + "\\");
    return targetDirectory.ToString();

Before using this method, you have to get the directory to the current execution file by the below way:

private string currentEXEFileDir = "";
currentEXEFileDir = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

As a conclusion, if you want to get the absolute path to the image named “picture.png”. You just pass two parameters to the above method like:

string path = getAbsoluteDir(currentEXEFileDir ,"..\\..\\Images\\picture.png");

I wish it would work well in your cases.:D

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: