[英]C#: Windows App Reading CSV file and Writing to a Console Issue
我有一個Windows Forms應用程序,該應用程序可以啟動調試控制台。 在應用程序中,通過單擊菜單,我讀取了一個CSV文件並將其寫入控制台。 執行此功能的功能如下。
protected void menuRead_Click(object sender, EventArgs e)
{
// ... functionality to load CSV files
System.IO.Stream inputDataFile = null;
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "c:\\";
fd.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
fd.FilterIndex = 1;
fd.RestoreDirectory = true;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if ((inputDataFile = fd.OpenFile()) != null)
{
inputData_exists = true;
// ... read input data from CSV file
using (CsvFileReader reader = new CsvFileReader(inputDataFile))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string s in row)
{
Console.Write(s);
Console.Write(" ");
}
Console.WriteLine();
}
// ... close the input data stream
inputDataFile.Close();
}
}
}
catch (Exception err)
{
//Inform the user if can't read the file
MessageBox.Show(err.Message);
}
}
}
除以下各項外,其他所有東西都可以正常工作:csv文件包含大約1200行代碼。 執行此代碼后,在csv文件內容開始寫入控制台窗口之前,OpenFileDialog()窗口僅部分關閉。 因此,我可以看到數據正在寫入控制台窗口,並且在窗體上顯示了對話框窗口的一小部分矩形。 有什么方法可以確保在將數據寫入控制台之前關閉對話框? 我應該打開一個新線程來與控制台通信嗎? 任何建議或幫助將不勝感激。 謝謝。
您的問題來自顯示控制台和ShowDialog調用的事實。 獲取Dialog的結果,然后打開控制台應用程序。 您還可以在我想的另一個線程上讀取文件。
您可以在這里使用很多方法。 最簡單的一種:使用StringBuilder,然后一次放置所有數據。 因為輸出到控制台的速度可能很慢。
StringBuilder consoleBuffer = new StringBuilder();
using (CsvFileReader reader = new CsvFileReader(inputDataFile))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string s in row)
{
consoleBuffer.Append(s);
consoleBuffer.Append(" ");
}
consoleBuffer.Append(Environment.NewLine);
}
Console.WriteLine(consoleBuffer.ToString());
// ... close the input data stream
inputDataFile.Close();
}
您需要花一些時間讓控件“ OpenFileDialog”在處理該控件時重新繪制自身,WinForm的最簡單方法是使用Application.DoEvents()
if (fd.ShowDialog() == DialogResult.OK)
{
Application.DoEvents();
...
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.