如何在 Windows 应用程序中的 UI 上显示文件计数
本文关键字:UI 显示文件 Windows 应用程序 | 更新日期: 2023-09-27 18:35:48
我要做的是每次读取文件时更新UI上的文件计数。同样,它甚至没有在UI上显示文件总数,当用户单击browseFolder事件的确定按钮时。任何帮助将不胜感激。以下是我的代码:
private void browse_Click(object sender, EventArgs e)
{
try
{
int fileCount = 0;
string newFileName1 = "";
string newFileName2 = "";
week = textBox2.Text;
if (week == null || week == "")
{
MessageBox.Show("Week cannot be null.");
return;
}
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
int j = 0;
int totalNoOfFiles = 0;
DateTime starttime = DateTime.Now;
string folderPath = folderBrowserDialog1.SelectedPath;
string folderName = Path.GetFileName(folderBrowserDialog1.SelectedPath);
totalNoOfFiles = Directory.GetFiles(folderPath, "*.txt", SearchOption.AllDirectories).Length;
lbltotalfiles.Text = Convert.ToString(totalNoOfFiles);
progressBar1.Minimum = 0;
progressBar1.Maximum = totalNoOfFiles;
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
foreach (DirectoryInfo folder in dInfo.GetDirectories())
{
newFileName1 = "Files_with_dates_mismatching_the_respective_week_" + folder.Name + ".txt";
newFileName2 = "Files_with_wrong_date_format_" + folder.Name + ".txt";
if (File.Exists(folderPath + "/" + newFileName1))
{
File.Delete(folderPath + "/" + newFileName1);
}
if (File.Exists(folderPath + "/" + newFileName2))
{
File.Delete(folderPath + "/" + newFileName2);
}
FileInfo[] folderFiles = folder.GetFiles();
if (folderFiles.Length != 0)
{
List<Task> tasks = new List<Task>();
foreach (var file in folderFiles)
{
fileCount = ++fileCount;
lblFilesRead.Text = Convert.ToString(fileCount);
progressBar1.Value = ++j;
var task = ReadFile(file.FullName, folderPath, folder.Name, week);
tasks.Add(task);
}
Task.WhenAll(tasks.ToArray());
DateTime stoptime = DateTime.Now;
TimeSpan totaltime = stoptime.Subtract(starttime);
label6.Text = Convert.ToString(totaltime);
textBox1.Text = folderPath;
}
}
DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception)
{
throw;
}
}
在读取/处理文件时,正在停止负责与用户交互/重新绘制组件的 Windows 事件队列。您应该不时调用:Application.DoEvents()
方法。它将允许应用程序处理消息,例如更新标签文本。
如果您想要一个非常好的用户体验,您应该使用另一个线程来处理文件,并从该线程使用label.BeginInvoke
方法来更新表单上的标签。这是很好的教程:http://www.codeproject.com/Articles/10311/What-s-up-with-BeginInvoke
你也可以看看FileSystemWatcher
类。从长远来看,这可能更容易维护......
class Program
{
static void Main(string[] args)
{
var watcher = new System.IO.FileSystemWatcher()
{
Path = @"G:'cc'",
};
watcher.Created += Watcher_Created;
watcher.EnableRaisingEvents = true;
Console.ReadKey();
}
private static void Watcher_Created(
object sender,
FileSystemEventArgs e
)
{
var folder = new DirectoryInfo(e.FullPath)
.Parent;
Console.WriteLine(
folder?
.GetFiles()
.Length
);
}
}