c# - 字符串在 C# 的末尾有一个换行符(无缘无故)
问题描述
我目前正在.NET 中编写一个从文件中读取的应用程序——在该文件中,有一个指向另一个文件的路径。然后应用程序打印该文件的内容。这是一个例子:
文件 1:
D:\Path\To\My\File.txt
SOME OTHER STUFF
文件 2:
Hello, world!
当我运行我的应用程序时,它会抛出一个错误,指出路径的语法无效。我尝试查看它从文件 1 中获取的实际字符串,所以我这样做了:
string testString = File.ReadAllText(file); // file is a variable that's already created, which is just a string with the path of File 1.
File.WriteAllText("test.txt", $"'{testString}'");
我查看了新创建的test.txt
并看到了这个。
'D:\Path\To\My\File.txt
'
为什么第二个引号之前有换行符?我尝试用谷歌搜索没有成功。请帮帮我,我是 C# 新手。
编辑1:
我尝试使用File.ReadAllBytes()
,但结果是一样的。
这是结果:
'D:\Georges\Desktop\G\test2.g
'
这是我的代码:
byte[] testString = File.ReadAllBytes(file);
File.WriteAllBytes("test.txt", testString);
编辑2:
当我从文件中删除除那一行之外的所有内容时,它起作用了。这很好,但我确实希望能够在我的文件中添加更多行而不使其不起作用。
解决方案
也许你应该使用File.ReadLines
而不是File.ReadAllText
. 像这样的东西:
string testString = File.ReadLines(file).ToList()[0]; // file is a variable that's already created, which is just a string with the path of File 1.
File.WriteAllText("test.txt", $"'{testString}'");
推荐阅读
- r - R Shiny - 控制我在数据表上的选择转到哪些数据表
- flutter - FutureBuilder 和相机
- javascript - 如何在 django 项目中的结帐会话后检索条带订阅 ID?
- typescript - Vercel deploy / build fail. "Failed to compile. Type error: Cannot find module ... or its corresponding type declarations
- date - Google 表格时间日期格式 2016-12-01T10:21:43.000Z 不被识别为 DATATIME
- javascript - 为什么在单击时将更改的值写入原始数组
- windows - 如何在 Windows 10 上使用 WiX 使程序在启动时运行(以管理员身份)
- css - 为什么我的样式化组件生成的类名会发生冲突?
- node.js - modbus-serial,有没有办法打开和关闭MobusTCP Server?
- javascript - 在任何嵌套级别上收集对象值