使用将文件添加到我的ListView
本文关键字:我的 ListView 添加 文件 | 更新日期: 2023-09-27 17:49:24
我想在我的应用程序中添加一个选项,将一个包含目录中所有文件的目录添加到我的ListView
中,因为我在添加到ListView
之前会检查每个文件(我的文件是Wiresark文件,所以我会检查文件扩展名,如果不是pcap格式,我会转换文件,然后添加(,我想用单独的线程来完成,所以我使用BackgroundWorker
,我需要如何做到这一点的一些帮助:
private void btnAddDir_Click(object sender, EventArgs e)
{
ListViewItem lv = new ListViewItem();
string fileToAdd = string.Empty;
List<string> filesList = new List<string>();
BackgroundWorker backgroundWorker = null;
DialogResult dialog = folderBrowserDialog1.ShowDialog();
if (dialog == DialogResult.OK)
{
Editcap editcap = new Editcap();
foreach (string file in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
{
if (editcap.isWiresharkFormat(file))
{
filesList.Add(file);
}
}
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s1, e1) =>
{
foreach (string fileName in filesList)
{
if (editcap.isWiresharkFormat(fileName))
{
if (editcap.isLibpcapFormat(fileName))
{
lv.Text = fileName;
lv.SubItems.Add(fileName);
lv.SubItems.Add("Waiting");
this.Invoke((MethodInvoker)delegate
{
lvFiles.Items.Add(lv);
});
lvFiles.Refresh();
}
}
}
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s1, e1) =>
{
});
backgroundWorker.RunWorkerAsync();
}
}
不要在backgroundWorker.ProgressChanged
事件中添加项目,而是在DoWork
中添加。
否则您将得到错误Cross-thread operation not valid: Control ___ accessed from a thread other than the thread it was created on.
更改
backgroundWorker.ReportProgress(0, fileToAdd);
至
lv.SubItems.Add(fileToAdd);
此外,您不需要处理ProgressChanged
和RunWorkerCompleted
事件。