首页 > 解决方案 > 为什么当我得到我的路径时会有第二个'\'

问题描述

我正在编写一个小程序,我想获取一个 txt 文件的路径。我得到了路径,但字符串变量的输出中总是有第二个“\”。

例如:

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

预期输出:'C:\Test\Test\Test\'

调试期间的输出:'C:\\Test\\Test\\Test\\'

当我使用时也是如此:

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

当我在调试期间运行我的应用程序时,无法打开 txt 文件,因为它进入了 IF 部分。

代码:

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();

txt 文件存储在项目文件夹中。

WinForms APP 是用 C# 和 .Net Framework 4.8 编写的

也许任何人都有一个想法。

先感谢您。

标签: c#

解决方案


IDE 将通过显示双反斜杠向您显示它已经转义了反斜杠。但是,字符串本身实际上并不包含双反斜杠。

这里有关于如何在 C# 中定义转义的更多信息

如果您要使用其他保留字符,您应该会在 IDE 中看到转义,就像您在双反斜杠中看到的那样,但不会在字符串的实际输出中看到。

例如:(反斜杠)在 IDE 中 - C:\\myfolder\\myfile.txt - 实际字符串输出 - C:\myfolder\myfile.txt

例如:(单引号)在 IDE 中 - "\'varValueWithSingleQuotes\'" - 实际字符串输出 - 'varValueWithSingleQuotes'


推荐阅读