我正在使用C#上的OpenFileDialog组件来选择要处理的多个文件。
问题在于,当程序完成foreach循环的执行时,它将重复执行“ private void openFileDialog1_FileOk(object sender,CancelEventArgs e)”方法,弄乱了我的excel电子表格。
如何处理?
这是我的代码:
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
int i = 2;
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
ws.Cells[1, 1] = "Test case";
ws.Cells[1, 2] = "Q Score";
ws.Cells[1, 3] = "TC Score";
foreach (String file in openFileDialog1.FileNames)
{
try
{
StreamReader arq = new StreamReader(file);
string Title = file;
Title = Title.Remove(0, Title.LastIndexOf("\\") + 1);
Title = Title.Remove(Title.LastIndexOf("."), Title.Length - Title.LastIndexOf("."));
string Title_aux = Title;
F.Text = "MSA-GA: " + Title;
string texto = arq.ReadToEnd();
arq.Close();
arq.Dispose();
openFileDialog1.Dispose();
texto = texto.Replace(" ","");
texto = texto.Replace("\r\n\r\n", "\r\n");
texto = texto.Replace("\r\n\r\n", "");
StreamWriter gravar = new StreamWriter(@"cases\" + Title + ".FASTA");
gravar.Write(texto);
gravar.Close();
gravar.Dispose();
string Title_ref = Title.Substring(0, (Title.Length - 2));
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c program -test cases\\" + Title + ".FASTA " + "-ref cases\\" + Title_ref;
//p.StartInfo.Arguments = "/C dir";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
int pos_ini = output.IndexOf("Q=")+2;
string q_score = output.Substring(pos_ini, (output.IndexOf(';', pos_ini) - pos_ini));
pos_ini = output.IndexOf("TC=") + 3;
string tc_score = output.Substring(pos_ini, (output.IndexOf("\r\n", pos_ini) - pos_ini));
q_score=q_score.Replace('.', ',');
tc_score=tc_score.Replace('.', ',');
ws.Cells[i, 1] = Title;
ws.Cells[i, 2] = q_score;
ws.Cells[i, 3] = tc_score;
i++;
}
catch
{
}
}
}
方法如下:
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
正在通过openFileDialog1.ShowDialog()
调用
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Fasta File";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.ShowDialog();
}
答案 0 :(得分:-1)
您的代码中肯定有一些问题,但您提到的不是。 ShowDialog()打开对话框并触发所有有线事件。因此,如果多次调用openFileDialog1_FileOk,请检查事件分配。右键单击Visual Studio中的openFileDialog1_FileOk方法,然后选择“查找所有引用”,检查是否有任何异常引用或其他内容。