Search code examples
c#escapingfileinfo

(C#) unescape string


i have the following piece of code:

string fFileName = @txtSelectedFolder.Text + "\\" + file.Name;

txtSelectedFolder.text contains nothing more than a path to a folder (for example: c:\temp\test)

file.name is a FileInfo type where name contains a reference to the current selected file in a collection of Files.

As soon as i use the above code, my fFileName var is filled with an escaped string like c:\\temp\\test\filename.ext

How can i make sure that fFileName contains the unescaped version of the filefolder (and name)


Solution

  • You aren't using a literal when adding in the extra wacks (\) . This will mean your string will escape the \ as it's being compiled and leave you with a single wack.

    Alter your line:

    string fFileName = @txtSelectedFolder.Text + "\\" + file.Name;
    

    to

    string fFileName = txtSelectedFolder.Text + @"\" + file.Name;
    

    You don't need the @ literal symbol infront of your variable.

    Alternatively:

    You can instead use

    string fFileName = Path.Combine(txtSelectedFolder.Text, file.Name);
    

    to properly concatenate the file's name to the selected file's path.