zoukankan      html  css  js  c++  java
  • 递归读取指定目录的文件和文件夹,并统计文件个数

    测试,递归读取指定目录的文件和文件夹,在WindowForm程序的测试开发。

    1.如果递归读取文件和文件夹

    2.如果使用 Func Action 委托。(参考:http://www.cnblogs.com/IAmBetter/archive/2012/02/13/2348912.html)

    3.委托异步处理数据,并获取返回值

    遇到错误就是 “线程间操作无效: 从不是创建控件的线程访问它”,使用空间提供的委托解决不再同一主线程的问题。

    http://msdn.microsoft.com/zh-cn/library/zyzhdc6b(VS.90).aspx#Y100

    参考代码如下。

    View Code
     1      private void button3_Click(object sender, EventArgs e)
    2 {
    3 var aaa = new Func<String, int>(GetFilesCount);
    4 aaa.BeginInvoke(textBox1.Text.Trim(), new AsyncCallback(Result), aaa);
    5
    6 }
    7
    8 public void Result(IAsyncResult result)
    9 {
    10 var aaa = (Func<String, int>)result.AsyncState;
    11 if (aaa != null)
    12 {
    13 if (label2.InvokeRequired)
    14 {
    15 var bb = new Action<String>(delegate(String str)
    16 {
    17 label2.Text = str;
    18 });
    19 label2.Invoke(bb, String.Format("{0} 个文件", aaa.EndInvoke(result)));
    20 }
    21 }
    22 }
    23
    24 public int GetFilesCount(String dirPath)
    25 {
    26 if (String.IsNullOrEmpty(dirPath)) return 0;
    27 int totalFile = 0;
    28 try
    29 {
    30 System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirPath);
    31 var fileList = dirInfo.GetFiles();
    32 foreach (var item in fileList)
    33 {
    34 if (listBox1.InvokeRequired)
    35 {
    36 var bb = new Action<String>(delegate(String str)
    37 {
    38 listBox1.Items.Add(str);
    39 });
    40 listBox1.Invoke(bb, String.Format("{0}", item.FullName));
    41 }
    42 }
    43 totalFile += fileList.Length;
    44
    45 foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories())
    46 {
    47 if (listBox1.InvokeRequired)
    48 {
    49 var bb = new Action<String>(delegate(String str)
    50 {
    51 listBox1.Items.Add(str);
    52 });
    53 listBox1.Invoke(bb, String.Format("{0}", subdir.FullName));
    54 }
    55 totalFile += GetFilesCount(subdir.FullName);
    56 }
    57 }
    58 catch (Exception)
    59 {
    60 }
    61 return totalFile;
    62 }

    自己测试参考,学习之用.如有不对地方,请包涵.

  • 相关阅读:
    常见保护方式简介
    各种保护机制绕过手法
    ShellCode框架(Win32ASM编写)
    单例模式
    HTTP1.0、HTTP1.1、HTTP2.0的关系和区别
    java集合提供的排序算法
    Dubbox以及微服务
    进程栈帧
    java线程池
    Java多态的实现
  • 原文地址:https://www.cnblogs.com/ksport/p/2427237.html
Copyright © 2011-2022 走看看