关于C# IO的使用

一、对于文件的操作

对于文件的操作,C#中就比较丰富了

FileSystemInfo
	FileInfo
	DirectoryInfo
File,Directory,DriverInfo, Path
对于文件、目录的操作是分开的,分别提供了静态类与普通类


二、对于文件读写的操作

首先C#与Java不同的地方,不再区分字符流、字节流,而统一采用Stream方式,然后针对Stream提供Reader与Writer的相关操作。

其类的个数也没有Java多

下面看看统计的相关类:

System.IO.Stream
  System.IO.BufferedStream
  System.IO.FileStream
  System.IO.MemoryStream
  System.Net.Sockets.NetworkStream
  System.Net.Sockets.UnmanagedMemoryStream
      System.IO.MemoryMappedFiles.MemoryMappedViewStream
  System.Security.Cryptography.CryptoStream
  System.IO.Compression.DeflateStream
  System.IO.Compression.GZipStream
  System.Net.Security.AuthenticatedStream
      System.Net.Security.NegotiateStream
      System.Net.Security.SslStream
  System.IO.Pipes.PipeStream
      System.IO.Pipes.AnonymousPipeServerStream
      System.IO.Pipes.AnonymousPipeClientStream
      System.IO.Pipes.NamedPipeServerStream
      System.IO.Pipes.NamedPipeClientStream
  System.Data.SqlTypes.SqlFileStream

System.IO.TextWriter
	System.IO.StringWriter
	System.IO.StreamWriter


System.IO.TextReader
	System.IO.StringReader
	System.IO.StreamReader

System.IO.BinaryWriter
System.IO.BinaryReader
上面的统计估计不是很完全,很可惜目前没有找到一张类图来展示


三、文件相关类的常用操作

1、查看文件驱动器以及下面的文件目录信息

using System;
using System.IO;
using System.Security.AccessControl;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                new Program().PrintFileTree();
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        /// <summary>
        /// 打印所有驱动器信息(包含里面的目录、文件)
        /// </summary>
        public void PrintFileTree()
        {
            DriveInfo[] drivers = DriveInfo.GetDrives();
            foreach (DriveInfo item in drivers)
            {
                if (item.DriveType == DriveType.CDRom)//光驱
                {
                    Console.WriteLine("光驱:" + item.Name);
                }
                else if (item.DriveType == DriveType.Fixed)//固定磁盘
                {
                    Console.WriteLine("固定磁盘:" + item.Name + "__" + item.RootDirectory);
                    PrintFileTree(item.RootDirectory);
                }
                else if (item.DriveType == DriveType.Network)//网络驱动器
                {
                    Console.WriteLine("网络驱动器:" + item.Name);
                }
                else if (item.DriveType == DriveType.NoRootDirectory)//驱动器没有根目录
                {
                    Console.WriteLine("驱动器没有根目录:" + item.Name);
                }
                else if (item.DriveType == DriveType.Ram)//RAM磁盘
                {
                    Console.WriteLine("RAM磁盘:" + item.Name);
                }
                else if (item.DriveType == DriveType.Removable)//可移动磁盘(软驱或者U盘等)
                {
                    Console.WriteLine("可移动磁盘(软驱或者U盘等):" + item.Name);
                }
                else if (item.DriveType == DriveType.Unknown)//未知类型
                {
                    Console.WriteLine("未知类型:" + item.Name);
                }
            }
        }
        /// <summary>
        /// 递归打印目录下面的信息
        /// </summary>
        /// <param name="dir">上级目录</param>
        public void PrintFileTree(DirectoryInfo dir)
        {

            //FileSystemAccessRule fsRule = new FileSystemAccessRule(System.Environment.UserName, FileSystemRights.Read, AccessControlType.Allow);

            ////添加安全访问规则 
            //DirectorySecurity dirSecurity = dir.GetAccessControl();
            //dirSecurity.AddAccessRule(fsRule);
            //dir.SetAccessControl(dirSecurity);

            //dir.GetAccessControl().GetAuditRules(true, true, typeof(System.Security.Principal.NTAccount));

            bool flag = true;
            foreach (FileSystemAccessRule item in dir.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                //拒绝读
                if (item.FileSystemRights == FileSystemRights.Read && item.AccessControlType == AccessControlType.Deny)
                {
                    flag = false;
                    break;
                }
            }

            if (flag)
            {
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo item in files)
                {
                    Console.WriteLine(item.FullName);
                }

                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo item in dirs)
                {
                    Console.WriteLine(item.FullName);
                    PrintFileTree(item);
                }
            }

            ////移除安全访问规则
            //dirSecurity = dir.GetAccessControl();
            //dirSecurity.RemoveAccessRule(fsRule);
            //dir.SetAccessControl(dirSecurity);           
        }
    }
}

2、常用文件操作方法

        public void Test1()
        {
            //写文件
            FileStream file = new FileStream("C:\\test1.txt", FileMode.OpenOrCreate);

            String text = @"更加务实的Surface
                          负责Surface业务的副总裁Panos Panay表示,他们的目标不是重新发明轮子,而是要大力改进它。从这句话也可以看得出,
                            这一代Surface不会给人们带来任何惊艳,取而代之的是务实的修改风,比如克服续航短板,带来更高的移动工作能力等。";
            byte[] array = System.Text.Encoding.UTF8.GetBytes(text);
            file.Write(array, 0, array.Length);
            file.Close();

            //读文件
            array = new byte[1024];
            file = new FileStream("C:\\test1.txt", FileMode.Open);
            while (file.Read(array, 0, 1024) > 0)
            {
                Console.Write(System.Text.Encoding.UTF8.GetString(array));
            }
            file.Close();
            Console.WriteLine("Test1完成操作");
        }

        public void Test2()
        {
            FileStream stream = new FileStream("C:\\test2.txt", FileMode.OpenOrCreate);
            StreamWriter writer = new StreamWriter(stream);
            writer.AutoFlush = true;
            for (int i = 0; i < 10; i++)
            {
                writer.WriteLine("不是重新发明轮子___" + i.ToString());
            }
            writer.Flush();
            writer.Close();
            stream.Close();


            StreamReader reader = new StreamReader("C:\\test2.txt");
            String str = String.Empty;
            while ((str = reader.ReadLine()) != null)
            {
                Console.WriteLine(str);
            }

            reader.Close();

            Console.WriteLine("Test2完成操作");

        }

        public void Test3()
        {
            //写文件
            FileStream file = new FileStream("C:\\test3.txt", FileMode.OpenOrCreate);
            BufferedStream writer = new BufferedStream(file, 1024);

            String text = @"要承认的是,设备的融合必将是未来的一种趋势,如今众多形态的计算设备,
                    如笔记本电脑、超级本和平板电脑未来很有可能融合成一个设备,这些设备的融合先决条件就是出现一个设备能将这些设备的形态和功能这两者囊括在一个中,
                    值得高兴的是,Surface就是拥有这种潜力的设备";
            byte[] array = System.Text.Encoding.UTF8.GetBytes(text);
            writer.Write(array, 0, array.Length);
            writer.Flush();
            writer.Close();
            file.Close();

            //读文件
            file = new FileStream("C:\\test3.txt", FileMode.Open);
            BufferedStream reader = new BufferedStream(file, 1024);

            array = new byte[1024];
            while (reader.Read(array, 0, 1024) > 0)
            {
                Console.Write(System.Text.Encoding.UTF8.GetString(array));
            }
            reader.Close();
            file.Close();

            Console.WriteLine("Test1完成操作");

        }

3、打文件复制操作方法

   public void BigFileCopy()
        {
            //每次读取的字节数  
            int MAX_BYTE = 1024 * 1024;
            byte[] array = new byte[MAX_BYTE];


            FileStream reader = new FileStream("C:\\infile.avi", FileMode.Open);
            FileStream writer = new FileStream("C:\\outfile.avi", FileMode.OpenOrCreate);

            //循环读取
            long total = reader.Length;
            for (long i = 0; i < total / MAX_BYTE; i++)
            {
                reader.Read(array, 0, MAX_BYTE);
                writer.Write(array, 0, MAX_BYTE);
                writer.Flush();
            }

            //不能整除导致剩余数据
            int level = (int)(total % MAX_BYTE);

            reader.Read(array, 0, level);
            writer.Write(array, 0, level);
            writer.Flush();

            //关闭流
            reader.Close();
            writer.Close();
            Console.WriteLine("BigFileCopy完成操作");
        }


………………………………

你可能感兴趣的:(关于C# IO的使用)