c# - 为什么当我得到我的路径时会有第二个'\'
问题描述
我正在编写一个小程序,我想获取一个 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 编写的
也许任何人都有一个想法。
先感谢您。
解决方案
IDE 将通过显示双反斜杠向您显示它已经转义了反斜杠。但是,字符串本身实际上并不包含双反斜杠。
这里有关于如何在 C# 中定义转义的更多信息。
如果您要使用其他保留字符,您应该会在 IDE 中看到转义,就像您在双反斜杠中看到的那样,但不会在字符串的实际输出中看到。
例如:(反斜杠)在 IDE 中 - C:\\myfolder\\myfile.txt - 实际字符串输出 - C:\myfolder\myfile.txt
例如:(单引号)在 IDE 中 - "\'varValueWithSingleQuotes\'" - 实际字符串输出 - 'varValueWithSingleQuotes'
推荐阅读
- android - 在谷歌地图上添加许多标记会导致地图移动粗略
- angular - 打字稿类型安全 - 服务不返回指定的类对象
- python - 过滤 Python 输出
- node.js - 当存在子集合时,为什么从 Firestore 检索的数据返回空数组?
- laravel - 同一控制器功能的多个路由
- javascript - Codeigniter 欢迎页面 JavaScript 通知程序
- javascript - 使用多维数组的登录页面?
- java - 如何通过标签名称检索多个标签中的元素以进行硒自动化测试
- localization - 使用清单的 MS Teams 应用本地化不起作用
- r - 将顶点属性数据从 igraph 移动到矩阵