码迷,mamicode.com
首页 > 其他好文 > 详细

递归和非递归遍历文件

时间:2016-11-06 14:07:22      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:info   遍历文件   log   文件   blog   text   pac   ogr   add   

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 遍历目录
{
    class Program
    {
        static void GetAllFiles(string dirPath)
        {

            List<string> list = new List<string>();
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            DirectoryInfo[] dirList = dir.GetDirectories();
            for (int i = 0; i < dirList.Length; i++)
            {
                list.Add(dirList[i].FullName);
                GetAllFiles(dirList[i].FullName);
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
        }
        static void GetAllFile2(string dirPath)
        {
            Stack<string> skDir = new Stack<string>();
            skDir.Push(dirPath);
            while (skDir.Count > 0)
            {
                dirPath = skDir.Pop();
                string[] subDirs = Directory.GetDirectories(dirPath);
                string[] subFiles = Directory.GetFiles(dirPath);
                if(subDirs != null)
                {
                    for (int i = 0; i < subDirs.Length; i++)
                    {
                        //Path.GetFileName(subDirs[i]);
                        skDir.Push(subDirs[i]);
                    }
                }
                if (subFiles != null)
                {
                    for (int i = 0; i < subFiles.Length; i++)
                    {
                        Console.WriteLine(subFiles[i]);
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            long startTime = DateTime.Now.Ticks;
            string dir = @"F:\开发资料";
            GetAllFile2(dir);
            long endTime = DateTime.Now.Ticks;
            Console.WriteLine("耗时{0}", endTime - startTime);
        }
    }
}

  

递归和非递归遍历文件

标签:info   遍历文件   log   文件   blog   text   pac   ogr   add   

原文地址:http://www.cnblogs.com/ZyCoder/p/6034951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!