Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a path work even if it contains an @ before "\\"

Tags:

string

c#

Im a bit confused. I thought "@" in c# ist a sign for to interpret text literally like @"C:\Users...". It avoids the need of a double backslash.

But why does paths also work if they contain double backslashes and the @? Fe:

var temp = File.ReadAllText(@"C:\\Users\\text.txt").ToString(); // no error

I that case the string must be literally "C:\\Users\\text.txt" - because of the previous "@" - which is not a valid windows path (EDIT: Thats wrong, it is a valid Path, only explorer wont accept it - thanks to Muctadir Dinar), so why does this work?

Thanks in advance

like image 648
BudBrot Avatar asked Sep 23 '13 12:09

BudBrot


1 Answers

Because internally FileStream during initialization calls iternal Path.NormalizePath(path, true, maxPathLength) method to normalize passed path value.

You can call this method with reflection (it has overload, so getting MethodInfo is a little bit tricky):

string path = @"C:\\Users\\text.txt";
Type type = typeof(Path);
var flags = BindingFlags.Static | BindingFlags.NonPublic;
var binder = Type.DefaultBinder;
var types = new Type[] { typeof(string), typeof(bool), typeof(int) };
var modifiers = new ParameterModifier[0];

var normalize = type.GetMethod("NormalizePath", flags, binder, types, modifiers);
var result = normalize.Invoke(null, new object[] { path, true, 256});

Output:

C:\Users\text.txt

like image 160
Sergey Berezovskiy Avatar answered Nov 15 '22 17:11

Sergey Berezovskiy