0
我正在制作一个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的文本文件,而我在使用它时会发生内存不足异常。我真的只想在合并文件时保持格式一致。