public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string strPath = "";
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog f = new FolderBrowserDialog();
f.ShowDialog();//==DialogResult.OK;
strPath = f.SelectedPath;
//progress();
progressBar1.Visible = true; ;
Thread myThread = new Thread(progress);
myThread.IsBackground = true;
myThread.Start();
}
public delegate void mydele(Dictionary<string, long> d, int i, string st, string PerCentage);
double percentage;
public void progress()
{
Dictionary<string, long> dic = new Dictionary<string, long>();
percentage = 0;
GetFile(strPath,dic,"");
if (dic!=null)
{
double i = 0.00d;
progressBar1.Maximum = dic.Count;
foreach (var item in dic)
{
i++;
double dvalue = i / dic.Count;
percentage = Math.Round((double)dvalue * 100, 2);///双精度浮点数控制
progressBar1.Value = int.Parse(i.ToString());
string strmsg = string.Format("{0}:文件名:{1}_大小:{2}
", "**", item.Key, item.Value);
//mydele md = new mydele(invokeShow);
//md.Invoke(dic, int.Parse(i.ToString()), strmsg, percentage.ToString()); ///同步
//mydele md = new mydele(invokeShow);
//md.BeginInvoke(dic, i, strmsg,null,new object[]{}); ///异步 常用
this.Invoke(new Action(delegate() ///异步
{
textBox1.Text += strmsg;
label1.Text = string.Format("总文件数{0} 已经读取到{1}个文件路径 进度{2}%", dic.Count, i, percentage);
}));
}
if (progressBar1.Value==progressBar1.Maximum)
{
progressBar1.Visible = false;
}
}
}
private void invokeShow(Dictionary<string, long> dic, int i, string strmsg,string strPerCentage)
{
try
{
textBox1.Text += strmsg;
label1.Text = string.Format("总文件数{0} 已经读取到第{1}个文件路径 进度{2}%", dic.Count, i, percentage);
if (progressBar1.Value == progressBar1.Maximum)
{
label1.Text = "读取完成";
}
}
catch (Exception)
{
}
}
/// <summary>
/// 获取路径下所有文件以及子文件夹中文件
/// </summary>
/// <param name="path">全路径根目录</param>
/// <param name="FileList">存放所有文件的全路径</param>
/// <param name="RelativePath"></param>
/// <returns></returns>
public Dictionary<string, long> GetFile(string path, Dictionary<string, long> FileList, string RelativePath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] fil = dir.GetFiles();
DirectoryInfo[] dii = dir.GetDirectories();
foreach (FileInfo f in fil)
{
//int size = Convert.ToInt32(f.Length);
long size = f.Length;
FileList.Add(f.FullName, size);//添加文件路径到列表中
}
//获取子文件夹内的文件列表,递归遍历
foreach (DirectoryInfo d in dii)
{
GetFile(d.FullName, FileList, RelativePath);
}
return FileList;
}
catch (Exception ex)
{
return null;
}
}
private void Form2_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
}
}