1

I'm reading an encoded string into memory and decode it. The string is something like "test\file1.txt".

Normally, C# would see this as string literal "test \\ file1.txt", correctly assigning an escape character to the backslash-char.

In this case, C# sees the slash as an escape character for the f from file. ("\f").

I can't use the Replace(@"\", @"\") method of string, because C# doesn't find "\", it only finds "\f". The filename is completely variable, so I can't use Replace(@"\f", @"\f") either...

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')

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):

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=="
4

1 回答 1

3

正如我一直怀疑的那样,创建文件的代码没有正确地转义反斜杠。

通过这样做来修复它,或者使用逐字字符串:

Utils.Encoder.Encode(@"test\file2.txt")

或通过显式转义反斜杠:

Utils.Encoder.Encode("test\\file2.txt")
于 2013-07-16T11:42:39.897 回答