Question

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=="
Was it helpful?

Solution

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top