简体   繁体   中英

Why is there an second '\' when I get my path

I'm writting a small program and I want to get the path of an txt file. I get the path, but there is always a second '\\' in the output of the string variable.

For example:

string path = @"C:\Test\Test\Test\"; 

expected output: 'C:\\Test\\Test\\Test\\'

Output during debug: 'C:\\\\Test\\\\Test\\\\Test\\\\'

The same is when I use:

public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

When I run my app during DEBUG, the txt file can not be opened, because it steps into the IF part.

Code:

public static readonly string AppRoot = Path . GetDirectoryName (Assembly.GetEntryAssembly().Location);

        FileStream fs;
        StreamReader sr;

        string dateiname = "anleitung.txt";
        string ausgabe;
        string path = Path.Combine(AppRoot, dateiname);

        if (!File.Exists(path))
            {
                MessageBox.Show("Die Datei '" + dateiname + "' existiert nicht!", "Fehler", MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }

        fs = new FileStream(dateiname, FileMode.Open);
        sr = new StreamReader(fs);

        ausgabe = "";
        while (sr.Peek() != -1)
            ausgabe += sr.ReadLine() + "\n";
        sr.Close();

The txt file is stored in the project folder.

The WinForms APP is written in C# with .Net Framework 4.8

Maybe anyone has an idea.

Thank you in advance.

The IDE will show you that it has escaped the backslashes by displaying the double backslash. However, the string itself does not actually contain double backslashes.

There is further information about how escaping is defined in C# here.

If you were to use other reserved characters you should see escaping in the IDE as you have seen for the double backslash, but not on the string's actual output.

eg:(backslashes) In IDE - C:\\\\myfolder\\\\myfile.txt - Actual string output - C:\\myfolder\\myfile.txt

eg:(single quote) In IDE - "\\'varValueWithSingleQuotes\\'" - Actual string output - 'varValueWithSingleQuotes'

A backslash in a string is an escape character so that you can include things like \\n (a newline) or \\t (a tab). If you want to include an actual backslash in the string you need to escape it with another backslash, ie \\\\

So you would write your string as:

string path = "C:\\Test\\Test\\Test\\";

But in your case you are using a verbatim string literal (the @ ) which treats escape sequences literally. So in that case you do not need to add the additional backslash in your line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM