递归遍历指定目录,获取该目录下最大的文件信息

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo maxFile = GetMaxFileInfo(new DirectoryInfo(@"e:\root\"), null);
            if (maxFile != null)
            {
                using (FileStream fsRead = new FileStream(maxFile.FullName, FileMode.Open))
                {
                    long fsLen = fsRead.Length;
                    byte[] heByte = new byte[fsLen];
                    int r = fsRead.Read(heByte, 0, heByte.Length);
                    string myStr = Encoding.Default.GetString(heByte);
                    Console.WriteLine(myStr);
                }
            }
            Console.Read();
        }

        public static FileInfo GetMaxFileInfo(FileSystemInfo info, FileInfo maxFile)
        {
            if (info.Exists == false) return null;
            DirectoryInfo dir = info as DirectoryInfo;
            if (dir == null) return null;
            FileSystemInfo[] files = dir.GetFileSystemInfos();
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = files[i] as FileInfo;
                if (file == null)
                {
                    maxFile = GetMaxFileInfo(files[i], maxFile);
                }
                else
                {
                    if (maxFile == null)
                    {
                        maxFile = file;
                    }
                    else if (maxFile.Length < file.Length)
                    {
                        maxFile = file;
                    }
                }
            }
            return maxFile;
        }
    }
}
posted @ 2016-02-02 15:45  云天  阅读(377)  评论(0编辑  收藏  举报