C#--文件操作+IOSerializable

1 文件及文件夹的操作

1.1 文件的常用操作

//获取当前应用程序所在路径  注意:不存在的文件路径创建DirectoryInfo时不会发生异常,所以需要在创建DirectoryInfo时进行Directory.Exists()判断
            string strCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
            Console.WriteLine(strCurrentPath);
            {
                if (!Directory.Exists(strCurrentPath))//检测文件夹是否存在
                {
                    Directory.CreateDirectory(strCurrentPath);//一次性创建全部的子路径
                    Directory.Move(strCurrentPath, "");//移动文件夹
                    Directory.Delete(strCurrentPath);//删除
                    
                }
                DirectoryInfo dirInfo = new DirectoryInfo(strCurrentPath);
                Console.WriteLine(string.Format("{0}{1}{2}", dirInfo.FullName,dirInfo.CreationTime,dirInfo.LastAccessTime));

            }


            {
                DriveInfo[] driveInfos = DriveInfo.GetDrives();
                foreach (DriveInfo item in driveInfos)
                {
                    if (item.IsReady)
                    {
                        Console.WriteLine("Type:{0},卷标:{1},Name:{2},总空间:{3},剩余空间:{4}", item.DriveType, item.VolumeLabel, item.Name, item.TotalSize, item.AvailableFreeSpace);
                    }
                    else
                    {
                        Console.WriteLine("Type:{0} is Ready",item.DriveType);
                    }
                }

            }

//2020-5-25 添加 
  #region 剪切非空目录
        /// <summary>
        /// 剪切非空目录
        /// </summary>
        /// <param name="strSourcePath">源文件夹</param>
        /// <param name="strDestPath">目标文件夹</param>
        public static void CutDirectory(string strSourcePath, string strDestPath)
        {
            //防呆:检查路径不存在
            if (!Directory.Exists(strSourcePath)||!Directory.Exists(strDestPath))
            {
                return;
            }
            DirectoryInfo sourcePathInfo = new DirectoryInfo(strSourcePath);
            //1、获取源路径名
            string srcxDirName = sourcePathInfo.Name;
            //2、根据源路径名称,创建新的目录(添加控制权限)
            string path = Path.Combine(strDestPath, srcxDirName);
            if (!Directory.Exists(path))
            {
                DirectorySecurity securityRules = new DirectorySecurity();
                securityRules.AddAccessRule(new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                Directory.CreateDirectory(path, securityRules);
            }
            //3、列出源文件夹所有子文件夹
            List<FileSystemInfo> files = GetListFiles(sourcePathInfo);
            foreach (FileSystemInfo fileInfo in files)
            {
                if (File.Exists(fileInfo.FullName))
                {
                    //如果是文件       
                    File.Move(fileInfo.FullName, Path.Combine(path, fileInfo.Name));
                }
                else if (Directory.Exists(fileInfo.FullName))
                {
                    //如果是文件夹
                    CutDirectory(fileInfo.FullName, path);
                }
            }
            //4、删除源文件目录
            Directory.Delete(strSourcePath, true);
        }
        #endregion

        //删除非空文件夹
        #region 删除给定目录下非空文件夹
        public static void DeleteDirectory(string strPath)
        {
            if (!Directory.Exists(strPath))
            {
                return;
            }
            DirectoryInfo directoryInfo = new DirectoryInfo(strPath);
            //1、列出所有子文件
            List<FileSystemInfo> files = GetListFiles(directoryInfo);
            foreach (FileSystemInfo fileInfo in files)
            {
                if (File.Exists(fileInfo.FullName))
                {
                    File.Delete(fileInfo.FullName);
                }
                else if (Directory.Exists(fileInfo.FullName))
                {
                    DeleteDirectory(fileInfo.FullName);
                }
            }
            Directory.Delete(strPath);
        }
        #endregion



        //列出文件夹的子孙文件与目录
        #region 列出文件夹的子孙文件与目录
        public static void ListFiles(DirectoryInfo directoryInfo, string strSpace)
        {
            List<FileSystemInfo> files = GetListFiles(directoryInfo);

            foreach (FileSystemInfo fileInfo in files)
            {
                if (File.Exists(fileInfo.FullName))
                {
                    Console.WriteLine($"{strSpace}+{fileInfo.Name}");
                }
                else if (Directory.Exists(fileInfo.FullName))
                {
                    Console.WriteLine($"{strSpace}+{fileInfo.Name}");
                    ListFiles(new DirectoryInfo(fileInfo.FullName), "|   " + strSpace);
                }
            }
        }
        #endregion

        //获取文件夹下文件和文件夹
        #region 获取文件夹下文件和文件夹
        private static List<FileSystemInfo> GetListFiles(DirectoryInfo directoryInfo)
        {
            List<FileSystemInfo> listFile = new List<FileSystemInfo>();
            DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();
            foreach (DirectoryInfo dirInfo in directoryInfos)
            {
                listFile.Add(dirInfo);
            }
            FileInfo[] fileInfos = directoryInfo.GetFiles();
            foreach (FileInfo fileInfo in fileInfos)
            {
                listFile.Add(fileInfo);
            }
            return listFile;
        }
        #endregion


       static void PrintFileVersionInfo(string path)
        {
            System.IO.FileInfo fileInfo = null;
            try
            {
                fileInfo = new System.IO.FileInfo(path);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                // 其他处理异常的代码
            }
            // 如果文件存在
            if (fileInfo != null && fileInfo.Exists)
            {
                System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(path);
                Console.WriteLine("文件名称=" + info.FileName);
                Console.WriteLine("产品名称=" + info.ProductName);
                Console.WriteLine("公司名称=" + info.CompanyName);
                Console.WriteLine("文件版本=" + info.FileVersion);
                Console.WriteLine("产品版本=" + info.ProductVersion);
                // 通常版本号显示为「主版本号.次版本号.生成号.专用部件号」
                Console.WriteLine("系统显示文件版本:" + info.ProductMajorPart + '.' + info.ProductMinorPart + '.' + info.ProductBuildPart + '.' + info.ProductPrivatePart);
                Console.WriteLine("文件说明=" + info.FileDescription);
                Console.WriteLine("文件语言=" + info.Language);
                Console.WriteLine("原始文件名称=" + info.OriginalFilename);
                Console.WriteLine("文件版权=" + info.LegalCopyright);

                Console.WriteLine("文件大小=" + System.Math.Ceiling(fileInfo.Length / 1024.0) + " KB");
            }
            else
            {
                Console.WriteLine("指定的文件路径不正确!");
            }
            // 末尾空一行
            Console.WriteLine();
        }



1.2 遍历文件夹中所有的子文件夹

  /// <summary>
        /// 遍历目录中的所有文件夹
        /// </summary>
        /// <param name="directoryInfoList">文件夹信息列表</param>
        /// <param name="directoryInfo">根文件夹信息</param>
        private void GetChildDirectoryInfo(List<DirectoryInfo> directoryInfoList,DirectoryInfo directoryInfo)
        {
            DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();//返回当前目录的子目录
            if (directoryInfos!=null&& directoryInfos.Length>0)
            {
                directoryInfoList.AddRange(directoryInfos);
                foreach (var item in directoryInfos)
                {
                    GetChildDirectoryInfo(directoryInfoList, item);
                }
            }
        }

1.3 获取计算机中的标卷

#region 计算机上的所有逻辑驱动器的驱动器名称
        private void Test03()
        {
            DriveInfo[] driveInfos = DriveInfo.GetDrives();
            foreach (var item in driveInfos)
            {
                if (item.IsReady)
                {
                    //1024b = 1k   1024k = 1M 1024M = 1G
                    Console.WriteLine($"type:{item.DriveType},卷标:{item.VolumeLabel},Name:{item.Name},总空间:{item.TotalSize / (1024 * 1024 * 1024)},剩余空间:{item.AvailableFreeSpace / (1024 * 1024 * 1024)}");
                }
                else
                {
                    Console.WriteLine($"Type:{item.DriveType} not Ready");
                }
            }
        } 
        #endregion

2 对象的序列化与反序列化

前期准备

class Constant
        {
            public static string g_strSerialDataPath = @"C:\Users\czswq\Desktop\test";
        }
[Serializable]//类的实例要被序列化,必须加序列化的特性
        class Programmer
        {
            [NonSerialized]//此字段不用序列化,并且只对字段有效
            public int ID = 1;
            public string Description { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
        }

        class DataFactory
        {
            public static List<Programmer> BuildProgrammerList()
            {
                List<Programmer> list = new List<Programmer>();
                list.Add(new Programmer() { ID=1,Description="教师",Name="李四",Sex="女"});
                list.Add(new Programmer() { ID =2, Description = "学生", Name = "张三", Sex = "男" });
                list.Add(new Programmer() { ID = 1, Description = "校长", Name = "王五", Sex = "女" });
                return list;
            }
        }


class JsonHelper
    {
        private static readonly object JavaScriptSerializer;

        //public static string ObjectToString<T>(T object)
        //{

        //}
        internal static string ObjectToString<T>(T programmerList)
        {
            //JavaScriptSerializer 需要System.Web.Extensions.dll
            JavaScriptSerializer jjs = new JavaScriptSerializer();
            return jjs.Serialize(programmerList);
            // throw new NotImplementedException();
        }
        
        internal static T StringToObject<T>(string strResult)
        {
            JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Deserialize<T>(strResult);
            //throw new NotImplementedException();
        }
        //需要NuGet  install_package Newtonsoft.Json
        public static string ToJson<T>(T obj)
        {
              return JsonConvert.SerializeObject(obj);
        }

        public static T ToObject<T>(string content)
        {
            return JsonConvert.DeserializeObject<T>(content);
        }
    }

2.1 二进制序列化器(文件乱码,看不懂)

  #region 使用二进制序列化对象
        private void BinarySerialize()
        {
            string fileName = Path.Combine(Constant.g_strSerialDataPath,@"kk.txt");

            //序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                //创建list集合
                List<Programmer> programmerList = DataFactory.BuildProgrammerList();
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(fStream, programmerList);
            }

            //反序列化
            using (Stream fStream = new FileStream(fileName,FileMode.Open,FileAccess.Read))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                fStream.Position = 0;//重置流位置
                //反序列化
                List<Programmer> list =  (List<Programmer>) binaryFormatter.Deserialize(fStream);
            }

        } 
        #endregion

二进制序列化文件

2.2 Soap序列化器

  #region Soap序列化器
        private void SoapSerialize()
        {
            string fileName = Path.Combine(Constant.g_strSerialDataPath, @"kkSoap.txt");

            //序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                //创建list集合
                List<Programmer> programmerList = DataFactory.BuildProgrammerList();
                //BinaryFormatter binaryFormatter = new BinaryFormatter();
                SoapFormatter soapFormatter = new SoapFormatter();
                //注意:SoapFormatter.Serialize 容器只不支持list 要转化为数组
                soapFormatter.Serialize(fStream, programmerList.ToArray());//(fStream, programmerList);
            }

            //反序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                //BinaryFormatter binaryFormatter = new BinaryFormatter();
                SoapFormatter soapFormatter = new SoapFormatter();
                fStream.Position = 0;//重置流位置
                //反序列化
                List<Programmer> list = ((Programmer[])soapFormatter.Deserialize(fStream)).ToList();
            }
        } 
        #endregion

Soap序列化文件

2.3 Xml序列化器

#region Xml序列化器
        private void XmlSerialize()
        {
            string fileName = Path.Combine(Constant.g_strSerialDataPath, @"kkXml.txt");

            //序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                //创建list集合
                List<Programmer> programmerList = DataFactory.BuildProgrammerList();
                //BinaryFormatter binaryFormatter = new BinaryFormatter();
                // SoapFormatter soapFormatter = new SoapFormatter();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Programmer>));
                //注意:SoapFormatter.Serialize 容器只不支持list 要转化为数组
                xmlSerializer.Serialize(fStream, programmerList);
            }

            //反序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                //BinaryFormatter binaryFormatter = new BinaryFormatter();
                //SoapFormatter soapFormatter = new SoapFormatter();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Programmer>));//创建Xml序列化容器
                fStream.Position = 0;//重置流位置
                //反序列化
                List<Programmer> list = (List<Programmer>)xmlSerializer.Deserialize(fStream);
            }
        } 
        #endregion

Xml序列化器

2.4 Json序列化对象

 #region Json序列化
        private void jsonSerialize()
        {
            List<Programmer> programmerList = DataFactory.BuildProgrammerList();
            string strResult = JsonHelper.ObjectToString<List<Programmer>>(programmerList);

            List<Programmer> list = JsonHelper.StringToObject<List<Programmer>>(strResult);
        } 
        #endregion
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值