日期:2014-05-17  浏览次数:20920 次

C#实现递归列目录

using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;

namespace TestApplicationFileSystem
{
    class Program
    {
       
        private static void ListFile(FileSystemInfo fileinfo,int level)
        {
            if (!fileinfo.Exists)
            {
                Console.Write("无此文件夹或路径");
                return;
            }
            else
            {
                string preStr = "";
                for (int i = 0; i < level; i++)
                {
                    preStr += "-";
                }
                DirectoryInfo di = fileinfo as DirectoryInfo;
                FileSystemInfo[] files = di.GetFileSystemInfos();
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo file = files[i] as FileInfo;
                    if (file != null)
                    {
                        Console.Write(" "+preStr+file.Name);
                        Console.Write("\n");
                    }
                    else
                    {
                        Console.Write(" "+preStr+files[i].Name + "(文件夹)");
                        Console.Write("\n");
                        ListFile(files[i],level+1);
                        
                       
                    }

                }
            }
            
        }
        static void Main(string[] args)
        {
            FileSystemInfo f = new DirectoryInfo("c:\\Test");
            ListFile(f,0);
            Console.ReadLine();
            
        }
    }
}
?