我正在尝试从某个位置浏览文件并希望在 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/