C# IO操作

2023-10-21 17:30:11 浏览数 (1)

1.  文件夹、文件的相关操作方法

代码语言:javascript复制
   /// <summary>
    /// 文件夹  文件管理
    /// 
    /// 会有一些在开发环境/测试环境/生产环境 不同,
    /// 数据库连接--路径--开关
    /// 配置文件:不用改代码编译
    /// 
    /// 配置路径:绝对路径      
    ///           相对路径 /  然后拼装
    ///           相当于应用程序所在路径
    ///           
    /// 配置文件最好有个集中管理的类
    /// 
    /// 
    /// </summary>
    public class MyIO
    {
        /// <summary>
        /// 配置绝对路径
        /// </summary>
        private static string LogPath = ConfigurationManager.AppSettings["LogPath"];
        private static string LogMovePath = ConfigurationManager.AppSettings["LogMovePath"];
        /// <summary>
        /// 获取当前程序路径
        /// </summary>
        private static string LogPath2 = AppDomain.CurrentDomain.BaseDirectory;

        /// <summary>
        /// 读取文件夹  文件信息
        /// </summary>
        public static void Show()
        {
            {//check
                if (!Directory.Exists(LogPath))//检测文件夹是否存在
                {

                }
                DirectoryInfo directory = new DirectoryInfo(LogPath);//不存在不报错  注意exists属性
                Console.WriteLine(string.Format("{0} {1} {2}", directory.FullName, directory.CreationTime, directory.LastWriteTime));

                if (!File.Exists(Path.Combine(LogPath, "info.txt")))
                {
                }

                FileInfo fileInfo = new FileInfo(Path.Combine(LogPath, "info.txt"));

                Console.WriteLine(string.Format("{0} {1} {2}", fileInfo.FullName, fileInfo.CreationTime, fileInfo.LastWriteTime));
            }
            {//Directory
                if (!Directory.Exists(LogPath))
                {
                    DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);//一次性创建全部的子路径
                    Directory.Move(LogPath, LogMovePath);//移动  原文件夹就不在了
                    Directory.Delete(LogMovePath);//删除
                }
            }
            {//File
                string fileName = Path.Combine(LogPath, "log.txt");
                string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
                string fileNameMove = Path.Combine(LogPath, "logMove.txt");
                bool isExists = File.Exists(fileName);
                if (!isExists)
                {
                    Directory.CreateDirectory(LogPath);//创建了文件夹之后,才能创建里面的文件
                    using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        string name = "12345567778890";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        fileStream.Write(bytes, 0, bytes.Length);
                        fileStream.Flush();
                    }
                    using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        StreamWriter sw = new StreamWriter(fileStream);
                        sw.WriteLine("1234567890");
                        sw.Flush();
                    }

                    using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string msg = "今天是Course6IOSerialize,今天上课的人有55个人";
                        sw.WriteLine(msg);
                        sw.Flush();
                    }
                    using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string name = "0987654321";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        sw.BaseStream.Write(bytes, 0, bytes.Length);
                        sw.Flush();
                    }



                    foreach (string result in File.ReadAllLines(fileName))
                    {
                        Console.WriteLine(result);
                    }
                    string sResult = File.ReadAllText(fileName);
                    Byte[] byteContent = File.ReadAllBytes(fileName);
                    string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);

                    using (FileStream stream = File.OpenRead(fileName))//分批读取
                    {
                        int length = 5;
                        int result = 0;

                        do
                        {
                            byte[] bytes = new byte[length];
                            result = stream.Read(bytes, 0, 5);
                            for (int i = 0; i < result; i  )
                            {
                                Console.WriteLine(bytes[i].ToString());
                            }
                        }
                        while (length == result);
                    }

                    File.Copy(fileName, fileNameCopy);
                    File.Move(fileName, fileNameMove);
                    File.Delete(fileNameCopy);
                    File.Delete(fileNameMove);//尽量不要delete
                }
            }

            {//DriveInfo
                DriveInfo[] drives = DriveInfo.GetDrives();

                foreach (DriveInfo drive in drives)
                {
                    if (drive.IsReady)
                        Console.WriteLine("类型:{0} 卷标:{1} 名称:{2} 总空间:{3} 剩余空间:{4}", drive.DriveType, drive.VolumeLabel, drive.Name, drive.TotalSize, drive.TotalFreeSpace);
                    else
                        Console.WriteLine("类型:{0}  is not ready", drive.DriveType);
                }

            }

            {
                Console.WriteLine(Path.GetDirectoryName(LogPath));  //返回目录名,需要注意路径末尾是否有反斜杠对结果是有影响的
                Console.WriteLine(Path.GetDirectoryName(@"d:\abc")); //将返回 d:
                Console.WriteLine(Path.GetDirectoryName(@"d:\abc"));// 将返回 d:abc
                Console.WriteLine(Path.GetRandomFileName());//将返回随机的文件名
                Console.WriteLine(Path.GetFileNameWithoutExtension("d:\abc.txt"));// 将返回abc
                Console.WriteLine(Path.GetInvalidPathChars());// 将返回禁止在路径中使用的字符
                Console.WriteLine(Path.GetInvalidFileNameChars());//将返回禁止在文件名中使用的字符
                Console.WriteLine(Path.Combine(LogPath, "log.txt"));//合并两个路径
            }
        }

2. 常见应用:找出一个文件夹中的所有子文件夹(找出所有文件方法与此类似)

代码语言:javascript复制
        /// <summary>
        /// 找出全部的子文件夹
        /// </summary>
        /// <param name="rootPath">根目录</param>
        /// <returns></returns>
        public static List<DirectoryInfo> GetAllDirectory(string rootPath)
        {
            if (!Directory.Exists(rootPath))
                return new List<DirectoryInfo>();

            List<DirectoryInfo> directoryList = new List<DirectoryInfo>();//容器
            DirectoryInfo directory = new DirectoryInfo(rootPath);//root文件夹
            directoryList.Add(directory);

            return GetChild(directoryList, directory);

          
        }

        /// <summary>
        /// 完成 文件夹--子目录--放入集合
        /// </summary>
        /// <param name="directoryList"></param>
        /// <param name="directoryCurrent"></param>
        /// <returns></returns>
        private static List<DirectoryInfo> GetChild(List<DirectoryInfo> directoryList, DirectoryInfo directoryCurrent)
        {
            var childArray = directoryCurrent.GetDirectories();
            if (childArray != null && childArray.Length > 0)
            {
                directoryList.AddRange(childArray);
                foreach (var child in childArray)
                {
                    GetChild(directoryList, child);
                }
            }
            return directoryList;
        }

0 人点赞