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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With