[英]C# extract escape character from string
我正在将编码的字符串读入内存并对其进行解码。 字符串类似于“test \\ file1.txt” 。
通常,C#会将此视为字符串文字“test \\\\ file1.txt” ,正确地将转义字符分配给反斜杠字符。
在这种情况下,C#将斜杠视为文件中f的转义字符。 (“\\F”)。
我不能使用字符串的Replace(@“\\”,@“\\”)方法,因为C#找不到“\\”,它只找到“\\ f”。 文件名是完全可变的,所以我不能使用Replace(@“\\ f”,@“\\ f”) ...
我将如何继续使用此内存中的字符串并添加斜杠,以便字符串是有效路径?
字符串只是从文本文件加载并通过解码器传递。
public static string Decode(string inp)
{
byte[] ToDecode = System.Convert.FromBase64String(inp);
return System.Text.ASCIIEncoding.UTF8.GetString(ToDecode);
}
这是我实际使用字符串的地方(称为'A')
foreach (string A in Attchmnts)
Msg.Attachments.Add(new Attachment(_AttachmentsPath + @"\" + A));
如果我通过立即检查附件的内容,结果如下:
?_AttachmentsPath + @"\" + A
"\\\\BUPC1537\\MailServer\\Attachments\\test\file2.txt"
我通过立即调用以下方法手动编码字符串(然后将该数据粘贴到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=="
正如我一直怀疑的那样,创建该文件的代码无法正确地转义反斜杠。
通过使用逐字符串来修复它:
Utils.Encoder.Encode(@"test\file2.txt")
或者通过显式转义反斜杠:
Utils.Encoder.Encode("test\\file2.txt")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.