当使用ReadAllLines()c#打开文本文件时,它会换行
本文关键字:文件 文本 换行 ReadAllLines | 更新日期: 2023-09-27 17:57:58
我创建了一个程序来制作bug模板,但遇到了文本保存不正确的问题。
我有一个名为TemplateTexts的文本文件,它保存了每个模板的所有文本,模板看起来像这样-
REQUIREMENTS
- Example
ADDITIONAL REQUIREMENTS
- Example
- Example
-----COPY BELOW THIS LINE-----
当程序关闭时,它会将所有这些复制到文本文件的一行中。(看起来像这样)
REQUIREMENTS- Example ADDITIONAL REQUIREMENTS- Example - Example-----COPY BELOW THIS LINE-----
文本文件包含20行模板。模板保存为文本文件中的一行文本,但当我再次打开程序时,它会将这一行文本转换为多行文本,就像第一个示例中的显示方式一样。
知道为什么会发生这种事吗?或者有没有更好的方法将每个模板保存到文本文件中,可能是用标志或其他东西将其分隔开?
这是我的程序代码:
public partial class Form1 : Form
{
static String buttonNamesPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonNames.txt";
String[] ButtonNames = System.IO.File.ReadAllLines(buttonNamesPath);
static String buttonTextPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonText.txt";
String[] ButtonText = System.IO.File.ReadAllLines(buttonTextPath);
private void SetupTextField()
{
comboBox1.Items.Clear();
comboBox2.Items.Clear();
for (int i = 0; i < ButtonNames.Length; i++)
{
comboBox1.Items.Insert(i, ButtonNames[i]);
comboBox2.Items.Insert(i, ButtonNames[i]);
}
}
public Form1()
{
InitializeComponent();
this.FormClosing += this.Form1_FormClosing;
}
private void Form1_Load(object sender, EventArgs e)
{
SetupTextField();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox1.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
ButtonNames[strIndex] = textBox1.Text;
ButtonText[strIndex] = richTextBox2.Text;
SetupTextField();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.IO.File.WriteAllLines(buttonNamesPath, ButtonNames);
System.IO.File.WriteAllLines(buttonTextPath, ButtonText);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox2.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
richTextBox1.Text = ButtonText[strIndex];
}
private void label3_Click(object sender, EventArgs e)
{
}
}
我还有两个名为ButtonNames.txt和ButtonText.txt的文本文件
当您向RichTextBox
询问其Text
属性时,它会将内部包含的富文本转换为纯文本字符串,显然在默认情况下,它会使用'n
来转换行尾。Notepad不将'n
识别为行尾(因为它正在寻找'r'n
的官方Windows行尾),所以它在一行中显示所有内容。如果要使用'r'n
保存行结尾,请对RichTextBox.Text
的结果使用string.Replace
,将'n
替换为'r'n
。
有关更多详细信息,请参阅此问题及其答案:
RichTextBox换行转换?