首页 > 解决方案 > 字符串在 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:

当我从文件中删除除那一行之外的所有内容时,它起作用了。这很好,但我确实希望能够在我的文件中添加更多行而不使其不起作用。

标签: c#

解决方案


也许你应该使用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}'");

推荐阅读