我制作了一个程序,扫描用户选择的文件夹,它将搜索MP3文件和WAV文件,然后它将计算这些文件的总大小,但当它完成所有这些程序是无响应标签将不会更新或只是一半,窗口无法拖动。
如何解决此问题?
编辑:
以下是检查文件大小的代码:
public string testFileSize(String dir)
{
if (MFILE_OPTION_SUBFOLDER_CHECKBOX.Checked == true)
{
double totalFileSize = 0;
if (MFILE_OPTION_MP3_CHECKBOX.Checked == true)
{
string[] files = System.IO.Directory.GetFiles(dir, "*.mp3", SearchOption.AllDirectories);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
}
if (MFILE_OPTION_WAV_CHECKBOX.Checked == true)
{
string[] files = System.IO.Directory.GetFiles(dir, "*.wav", SearchOption.AllDirectories);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
}
totalFileSize = Math.Round((totalFileSize / 1024f) / 1024f, 2);
return totalFileSize.ToString() + " MB";
}
else
{
double totalFileSize = 0;
if (MFILE_OPTION_MP3_CHECKBOX.Checked == true)
{
string[] files = System.IO.Directory.GetFiles(dir, "*.mp3", SearchOption.TopDirectoryOnly);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
}
if (MFILE_OPTION_WAV_CHECKBOX.Checked == true)
{
string[] files = System.IO.Directory.GetFiles(dir, "*.wav", SearchOption.TopDirectoryOnly);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
}
totalFileSize = Math.Round((totalFileSize / 1024f) / 1024f, 2);
return totalFileSize.ToString() + " MB";
}
}
这是我尝试的但是它们具有如上所示的所有文件类型^^
if (MFILE_OPTION_WAV_CHECKBOX.Checked == true)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
string[] files = System.IO.Directory.GetFiles(dir, "*.wav", SearchOption.TopDirectoryOnly);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
};
bw.RunWorkerAsync();
}
但是这会返回0 MB怎么样?
答案 0 :(得分:3)
您应该使用BackgroundWorker
。如果您提供一些代码,我们可以帮助您更好。到目前为止,我只能给你这个:
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s,e) =>
{
// Do your work
};
bw.RunWorkerAsync();
基于您的代码的示例:
if (MFILE_OPTION_WAV_CHECKBOX.Checked == true)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
string[] files = System.IO.Directory.GetFiles(dir, "*.wav", SearchOption.TopDirectoryOnly);
foreach (string fileName in files)
{
FileInfo fi = new FileInfo(fileName);
double fileSize = fi.Length;
totalFileSize += fileSize;
}
};
bw.RunWorkerCompleted += (s,e) =>
{
//Update GUI
}
bw.RunWorkerAsync();
}
答案 1 :(得分:1)
您需要使用BackgroundWorker
或类似的东西。
您的表单没有响应,因为您在与用户界面相同的线程中执行主要工作,这就是它没有响应的原因。
如果您想在搜索文件的过程中更新用户界面,还需要使用Invokes
来更改值