Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd C# path issue

Tags:

c

string

c#

path

slash

My C# application writes its full path surrounded by double quotes to a file, with:

streamWriter.WriteLine("\"" + Application.ExecutablePath + "\"");

Normally it works, the written file contains

"D:\Dev\Projects\MyApp\bin\Debug\MyApp.exe"

But, if the executable path of my application contains a #, something weird happens. The output becomes:

"D:\Dev\Projects#/MyApp/bin/Debug/MyApp.exe"

The slashes after the # become forward slashes. This causes issues with the system I am developing.

Why is this happening, and is there a way to prevent it that is more elegant than string.replacing the path before writing?

like image 533
Ryan Avatar asked Oct 18 '12 01:10

Ryan


People also ask

What is odd number in C?

Program to Check Even or Odd Then, whether num is perfectly divisible by 2 or not is checked using the modulus % operator. If the number is perfectly divisible by 2 , test expression number%2 == 0 evaluates to 1 (true). This means the number is even.

What is odd loop in C?

Sometimes a user may not know about how many times a loop is to be executed. If we want to execute a loop for unknown number of times, then the concept of odd loops should be implemented. This can be done using for-loop, while-loop or do-while-loops.

Is 0 Even or odd in C?

Zero is an even number.


Video Answer


1 Answers

I just looked into the source code of Application.ExecutablePath, and the implementation is essentially this*:

Assembly asm = Assembly.GetEntryAssembly();
string cb = asm.CodeBase;
var codeBase = new Uri(cb); 

if (codeBase.IsFile) 
    return codeBase.LocalPath + Uri.UnescapeDataString(codeBase.Fragment);
else
    return codeBase.ToString();

The property Assembly.CodeBase will return the location as an URI. Something like:

file:///C:/myfolder/myfile.exe

The # is the fragment marker in a URI; it marks the beginning of the fragment. Apparently, the Uri class alters the given uri when it's parsed and converted back to a string again.

Since Assembly.Location contains a 'normal' file path, I guess your best alternative is:

string executablePath = Assembly().GetEntryAssembly().Location;

*) The implementation is more complex than this, because it also deals with situations where there are multiple appdomains and other special situations. I simplified the code for the most common situation.

like image 149
Elian Ebbing Avatar answered Sep 30 '22 10:09

Elian Ebbing