如何读取/显示文件中的\ n文本作为换行符?

时间:2018-09-23 23:04:32

标签: c# file-io text-files newline

我最近开始使用C#进行编码,而我的基于文本的游戏却遇到了一个奇怪但又麻烦的问题。

该文本文件不会将我写在文本文件中的“ \ n”文字打印为新行。我无法放置实际行,因为ReadAllLines()无法再正确拆分描述。

这是一个表达我的意思的例子

在roomdata.txt中

You see an inn to the east, the everywhere else is covered in nothing but trees.\nYoucan make out a windmill and a pond in the entrance to the village.
You stand in a flat terrain spotted with unusual colorful stones.\nYou can see a tower miles away. The village is east of here.

主要

string[] roomsdata = File.ReadAllLines("roomdata.txt");
Console.WriteLine(roomsdata[0])

它将在文本中打印“ \ n”,而不是实际创建新行。

1 个答案:

答案 0 :(得分:1)

您可以使用Replace方法将文字\n转换为换行符转义序列:

roomsdata[0].Replace("\\n", "\n")
  

“ \ n”将添加一个额外的“ \”

什么都不会添加到实际字符串中。由于文件包含\n literal ,因此调试器将显示转义的版本。因此,在这种情况下为\\n,显示为\n

如果要用换行符替换\n's,则应使用Environment.NewLine

roomsdata[0].Replace("\\n", Environment.NewLine)