c# - 刷新 Windows 窗体中的 list 框

标签 c# .net list windows-forms-designer

我正在尝试从某个位置浏览文件并希望在 Windows 窗体 list 框中显示它。它应该可以在目录中添加和删除文件。我试过一个骗子

private void timer1_Tick(object sender, EventArgs e)
{
    PopulateListBoxIsRefresh(chklistscripts, Helper.ScriptPath, "*.sql");
    chklistscripts.Refresh();
}

private void PopulateListBoxIsRefresh(ListBox lsb, string Folder, string FileType)
{
    DirectoryInfo dinfo = new DirectoryInfo(Folder);
    FileInfo[] files = dinfo.GetFiles(FileType);

    foreach (FileInfo file in files.OrderByDescending(p => p.CreationTime))
    {
        if (!File.Exists(file.FullName))
        {
            lsb.Items.Add(file.Name);
        }
    }
}

解决它的最简单调整是什么。

我想要以下场景。

没有文件 文件添加 文件删除

最佳答案

您可以像这样使用 FileSystemWatcher:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Folder;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | 
               NotifyFilters.DirectoryName | NotifyFilters.FileName;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;

详情请见https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

最好使用异步事件处理程序而不是将 CPU 周期浪费在轮询上。

关于c# - 刷新 Windows 窗体中的 list 框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34300108/

相关文章:

python - 如何查找字符串中某个字符所有出现的索引?

r - 将列表列表的维度组合成单独的向量

c# - 将离线(本地桌面应用程序)数据库与中央服务器和多台电脑同步的最简单解决方案?

c# - 在泛型方法中调用特定实现

.net - 从 .ebextensions 中的 Elastic Beanstalk 读取环境属性

c# - 方法 GetPrice() 无法转换为商店表达式

jquery - 删除列表中的最后一个子项

c# - 是否可以在不安装 Selenium Server 的情况下使用 ISelenium/DefaultSelenium?

c# - 是否可以在 OSX 上的 Mono 或 .NET 中从 Unity C# 运行 R 代码?

c# - 并行异步任务的任务调度程序