我正在制作一个WPF程序,现在我希望能够打开和合并文件。我有一个打开文件的按钮,我有一个合并文件的按钮,当我没有实现“onTextChanged”方法时,两个按钮都正常工作,文件格式正确。但是,如果我实现onTextChanged方法并使用合并文件按钮,则前一个“文件”会在其输出中获得额外的行。
打开按钮代码:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
合并按钮代码:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
当我执行此代码时,它会在最后一个'文件输出:
之间添加行private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
如果您想知道为什么我不使用字符串的Split方法,那是因为我需要打开50+ MB文本文件,并且在使用它时会出现内存不足异常。我真的只想在合并文件时保持格式相同。
答案 0 :(得分:1)
哇,这是一线修复。
原始代码行:
buffer.Add(sb.ToString());
更改(更正)代码行:
buffer.Add(sb.ToString().Trim());
变化有效,但是如果有人知道这些额外的线路来自何处会有所帮助。