Reputation: 112
I have the following:
// Get my executable's path
string exeFile = ( new System.Uri( Assembly.GetEntryAssembly().CodeBase ) ).AbsolutePath;
// Get its directory
string exeFolder = Path.GetDirectoryName( exeFile );
// Get rid of those %20 and stuff
exeFolder = Uri.UnescapeDataString( exeFolder );
// Get some relative path from my .config file
string relativePath = ConfigurationManager.AppSettings["MyRelativePath"] );
// Woa. The final result, uff.
string myFinalPath = Path.Combine( exeFolder, relativePath );
Now, if MyRelativePath is something like ..\Xpto\PleaseReadMe.txt
and my executable is located in C:\Ypto\RunMe.exe
, I will end with:
C:\Ypto\..\Xpto\PleaseReadMe.txt
instead of
C:\Xpto\PleaseReadeMe.txt
Considering that I must present this path in a textbox, of course I don't want users to see the ugly "\Ypto.." part. I can easily make a function with a few lines to parse this string and remove these constructions, but I wonder if there is a C# method that elegantly does this. If not, what algorithm do you recommend?
Thank you!
Upvotes: 0
Views: 97
Reputation: 57976
You can go with Path.GetFullPath
method. Also, you can remove the Uri
handling:
// Get my executable's path
string exeFile = Assembly.GetEntryAssembly().Location;
// Get its directory
string exeFolder = Path.GetDirectoryName( exeFile );
// Get some relative path from my .config file
string relativePath = @"..\Xpto\PleaseReadMe.txt";
// Woa. The final result, uff.
string myFinalPath = Path.GetFullPath(Path.Combine(exeFolder, relativePath));
Console.WriteLine(myFinalPath);
Sample test:
@DEBUG\ConsoleApplication1.exe
Output:
C:\ConsoleApplication1\ConsoleApplication1\bin\Xpto\PleaseReadMe.txt
Upvotes: 1