[英]C# extract escape character from string
I'm reading an encoded string into memory and decode it. 我正在将编码的字符串读入内存并对其进行解码。 The string is something like "test\\file1.txt" .
字符串类似于“test \\ file1.txt” 。
Normally, C# would see this as string literal "test \\\\ file1.txt" , correctly assigning an escape character to the backslash-char. 通常,C#会将此视为字符串文字“test \\\\ file1.txt” ,正确地将转义字符分配给反斜杠字符。
In this case, C# sees the slash as an escape character for the f from file. 在这种情况下,C#将斜杠视为文件中f的转义字符。 ("\\f").
(“\\F”)。
I can't use the Replace(@"\\", @"\\") method of string, because C# doesn't find "\\", it only finds "\\f". 我不能使用字符串的Replace(@“\\”,@“\\”)方法,因为C#找不到“\\”,它只找到“\\ f”。 The filename is completely variable, so I can't use Replace(@"\\f", @"\\f") either...
文件名是完全可变的,所以我不能使用Replace(@“\\ f”,@“\\ f”) ...
How would I proceed with this in-memory string and add a slash, so that the string is a valid path? 我将如何继续使用此内存中的字符串并添加斜杠,以便字符串是有效路径?
The string is just loaded from a text-file and passed through a decoder. 字符串只是从文本文件加载并通过解码器传递。
public static string Decode(string inp)
{
byte[] ToDecode = System.Convert.FromBase64String(inp);
return System.Text.ASCIIEncoding.UTF8.GetString(ToDecode);
}
This is where I actually use the string (which is called 'A') 这是我实际使用字符串的地方(称为'A')
foreach (string A in Attchmnts)
Msg.Attachments.Add(new Attachment(_AttachmentsPath + @"\" + A));
If I check the contents of the Attachment, via immediate, this is the result: 如果我通过立即检查附件的内容,结果如下:
?_AttachmentsPath + @"\" + A
"\\\\BUPC1537\\MailServer\\Attachments\\test\file2.txt"
I have manually encoded the string by calling following method in immediate (and then pasting that data into an XML document): 我通过立即调用以下方法手动编码字符串(然后将该数据粘贴到XML文档中):
public static string Encode(string inp)
{
byte[] ToEncode = System.Text.ASCIIEncoding.UTF8.GetBytes(inp);
return System.Convert.ToBase64String(ToEncode);
}
//Immediate code
?Utils.Encoder.Encode("test\file2.txt")
"dGVzdAxpbGUyLnR4dA=="
As I suspected all along, the code that creates the file doesn't correctly escape the backslash. 正如我一直怀疑的那样,创建该文件的代码无法正确地转义反斜杠。
Fix it by doing so, either by using a verbatim string: 通过使用逐字符串来修复它:
Utils.Encoder.Encode(@"test\file2.txt")
or by explicitly escaping the backslash: 或者通过显式转义反斜杠:
Utils.Encoder.Encode("test\\file2.txt")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.