C#中简单的文件操作实例

using System;
using System.IO;

namespace Demo
{
    class Program
    {
        static string tmpPath = @"D:/LgsTest/DiretoryTest";
        static void Main(string[] args)
        {
            //CreateDirectory(tmpPath);
            ErgodicDirectory(@"D:\LgsTest\C#练习\ShenRuLiJieC#");
            Console.ReadKey();
        }

        //判断指定的路径是否存在,存在的话将删除重新创建,否则只是创建
        static void CreateDirectory(string path)
        {
            //判断给定的路径是否存在,注意只能判断路径(即文件夹), 不具体到文件!!!
            if (Directory.Exists(tmpPath))
            {
                DirectoryInfo dic = new DirectoryInfo(tmpPath);
                //指定是否删除子目录和文件,若为 true,则删除此目录、其子目录以及所有文件
                //若为 false,目录不为空会报异常,即只能当目录为空的时候可以传 false
                dic.Delete(true);
            }
            else
            {
                Console.WriteLine(false);
            }

            //创建目录
            Directory.CreateDirectory(tmpPath);
        }

        //递归遍历某个目录,输出其中及其子目录中的文件名
        static void ErgodicDirectory(string path)
        {
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                if (null != dir)
                {
                    //返回表示某个目录中所有文件和子目录的强类型 System.IO.FileSystemInfo 项的数组。
                    FileSystemInfo[] fileSystemInfo = dir.GetFileSystemInfos();
                    for (int i = 0, iMax = fileSystemInfo.Length; i < iMax; ++i)
                    {
                        FileSystemInfo tmpFile = fileSystemInfo[i];
                        //组合路径
                        string tmpPath = Path.Combine(path, tmpFile.Name);

                        if (tmpFile is DirectoryInfo)
                        {
                            ErgodicDirectory(tmpPath);
                        }
                        else
                        {
                            //输出文件名
                            Console.WriteLine(tmpFile.Name);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("wwwww");
                }
            }
            else
            {
                Console.WriteLine("qqqq");
            }
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/9136468.html