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的文本文件,而我在使用它時會發生內存不足異常。我真的只想在合併文件時保持格式一致。