zoukankan      html  css  js  c++  java
  • C#常用IO流与读写文件

    1.文件系统
    
    (1)文件系统类的介绍
        文件操作类大都在System.IO命名空间里。FileSystemInfo类是任何文件系统类的基类;FileInfo与File表示文件系统中的文件;DirectoryInfo与Directory表示文件系统中的文件夹;Path表示文件系统中的路径;DriveInfo提供对有关驱动器的信息的访问。注意,XXXInfo与XXX类的区别是:XXX是静态类,XXXInfo类可以实例化。
        还有个较为特殊的类System.MarshalByRefObject允许在支持远程处理的应用程序中跨应用程序域边界访问对象。 
    (2)FileInfo与File类
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo file = new FileInfo(@"E:学习笔记C#平台	est.txt");//创建文件
            Console.WriteLine("创建时间:" + file.CreationTime);
            Console.WriteLine("路径:" + file.DirectoryName);
            StreamWriter sw = file.AppendText();//打开追加流
            sw.Write("李志伟");//追加数据
            sw.Dispose();//释放资源,关闭文件
            File.Move(file.FullName, @"E:学习笔记	est.txt");//移动
            Console.WriteLine("完成!");
            Console.Read();
        }
    }
    (3)DirectoryInfo与Directory类
    class Program
    {
        static void Main(string[] args)
        {
            //创建文件夹
            DirectoryInfo directory = new DirectoryInfo(@"E:学习笔记C#平台	est");
            directory.Create();
            Console.WriteLine("父文件夹:" + directory.Parent.FullName);
            //输出父目录下的所有文件与文件夹
            FileSystemInfo[] files = directory.Parent.GetFileSystemInfos();
            foreach (FileSystemInfo fs in files)
            {
                Console.WriteLine(fs.Name);
            }
            Directory.Delete(directory.FullName);//删除文件夹
            Console.WriteLine("完成!");
            Console.Read();
        }
    }
    (4)Path类
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Path.Combine(@"E:学习笔记C#平台", @"TestTest.TXT"));//连接
            Console.WriteLine("平台特定的字符:" + Path.DirectorySeparatorChar);
            Console.WriteLine("平台特定的替换字符:" + Path.AltDirectorySeparatorChar);
            Console.Read();
        }
    }
    (5)DriveInfo类
    class Program
    {
        static void Main(string[] args)
        {
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo d in drives)
            {
                if (d.IsReady)
                {
                    Console.WriteLine("总容量:" + d.TotalFreeSpace);
                    Console.WriteLine("可用容量:" + d.AvailableFreeSpace);
                    Console.WriteLine("驱动器类型:" + d.DriveFormat);
                    Console.WriteLine("驱动器的名称:" + d.Name + "
    ");
                }
            }
            Console.WriteLine("OK!");
            Console.Read();
        }
    }
    回到顶部
    2.文件操作
    
    (1)移动、复制、删除文件
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:学习笔记C#平台Test.txt";
            File.WriteAllText(path, "测试数据");
            Console.WriteLine("文件已创建,请查看!");
            Console.ReadLine();
            File.Move(path, @"E:学习笔记Test.txt");
            Console.WriteLine("移动完成,请查看!");
            Console.ReadLine();
            File.Copy(@"E:学习笔记Test.txt", path);
            Console.WriteLine("文件已复制,请查看!");
            Console.ReadLine();
            File.Delete(path);
            File.Delete(@"E:学习笔记Test.txt");
            Console.WriteLine("文件已删除,请查看!
    OK!");
            Console.Read();
        }
    }
    (2)判断是文件还是文件夹
    class Program
    {
        static void Main(string[] args)
        {
            IsFile(@"E:学习笔记C#平台Test.txt");
            IsFile(@"E:学习笔记");
            IsFile(@"E:学习笔记XXXXXXX");
            Console.Read();
        }
        //判断路径是否是文件或文件夹
        static void IsFile(string path)
        {
            if (Directory.Exists(path))
            {
                Console.WriteLine("是文件夹!");
            }
            else if (File.Exists(path))
            {
                Console.WriteLine("是文件!");
            }
            else
            {
                Console.WriteLine("路径不存在!");
            }
        }
    }
    回到顶部
    3.读写文件与数据流
    
    (1)读文件
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:学习笔记C#平台Test.txt";
            byte[] b = File.ReadAllBytes(path);
            Console.WriteLine("ReadAllBytes读二进制:");
            foreach (byte temp in b)
            {
                Console.Write((char)temp+" ");
            }
            string[] s = File.ReadAllLines(path, Encoding.UTF8);
            Console.WriteLine("
    ReadAllLines读所有行:");
            foreach (string temp in s)
            {
                Console.WriteLine("行:"+temp);
            }
            string str = File.ReadAllText(path, Encoding.UTF8);
            Console.WriteLine("ReadAllText读所有行:
    " + str);
            Console.Read();
        }
    }
    (2)写文件
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:学习笔记C#平台Test.txt";
            File.WriteAllBytes(path,new byte[] {0,1,2,3,4,5,6,7,8,9});//写入二进制
            Console.WriteLine("WriteAllBytes写入二进制成功");
            Console.ReadLine();
            string[] array = {"123","456","7890"};
            File.WriteAllLines(path, array, Encoding.UTF8);//写入所有行
            Console.WriteLine("WriteAllLines写入所有行成功");
            Console.ReadLine();
            File.WriteAllText(path, "abcbefghijklmn",Encoding.UTF8);//写入字符串
            Console.WriteLine("WriteAllText写入字符串成功
    OK!");
            Console.Read();
        }
    }
    (3)数据流
        最常用的流类如下:
            FileStream:     文件流,可以读写二进制文件。 
            StreamReader:   流读取器,使其以一种特定的编码从字节流中读取字符。 
            StreamWriter:   流写入器,使其以一种特定的编码向流中写入字符。 
            BufferedStream: 缓冲流,给另一流上的读写操作添加一个缓冲层。
        数据流类的层次结构:
     
    (4)使用FileStream读写二进制文件
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:学习笔记C#平台Test.txt";
            //以写文件的方式创建文件
            FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
            string str = "测试文件--李志伟";
            byte[] bytes = Encoding.Unicode.GetBytes(str);
            file.Write(bytes, 0, bytes.Length);//写入二进制
            file.Dispose();
            Console.WriteLine("写入数据成功!!!");
            Console.ReadLine();
            //以读文件的方式打开文件
            file = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] temp = new byte[bytes.Length];
            file.Read(temp, 0, temp.Length);//读取二进制
            Console.WriteLine("读取数据:" + Encoding.Unicode.GetString(temp));
            file.Dispose();
            Console.Read();
        }
    }
    (5)StreamWriter与StreamReader
        使用StreamWriterStreamReader就不用担心文本文件的编码方式,所以它们很适合读写文本文件。
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:学习笔记C#平台Test.txt";
            //以写文件的方式创建文件
            FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            sw.WriteLine("测试文件--李志伟");
            sw.Dispose();
            Console.WriteLine("写入数据成功!!!");
            Console.ReadLine();
            //以读文件的方式打开文件
            file = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            Console.WriteLine("读取数据:"+sr.ReadToEnd());
            sr.Dispose();
            Console.Read();
        }
    }
    回到顶部
    4.映射内存的文件
    
    (1)MemoryMappedFile类(.NET4新增)
        应用程序需要频繁地或随机地访问文件时,最好使用MemoryMappedFile类(映射内存的文件)。使用这种方式允许把文件的一部分或者全部加载到一段虚拟内存上,这些文件内容会显示给应用程序,就好像这个文件包含在应用程序的主内存中一样。
    (2)使用示例
    class Program
    {
        static void Main(string[] args)
        {
            MemoryMappedFile mmfile = MemoryMappedFile.CreateFromFile(@"E:Test.txt", FileMode.OpenOrCreate, "MapName", 1024 * 1024);
            MemoryMappedViewAccessor view = mmfile.CreateViewAccessor();//内存映射文件的视图
            //或使用数据流操作内存文件
            //MemoryMappedViewStream stream = mmfile.CreateViewStream();
            string str = "测试数据:李志伟!";
            int length = Encoding.UTF8.GetByteCount(str);
            view.WriteArray<byte>(0, Encoding.UTF8.GetBytes(str), 0, length);//写入数据
            byte[] b = new byte[length];
            view.ReadArray<byte>(0, b, 0, b.Length);
            Console.WriteLine(Encoding.UTF8.GetString(b));
            mmfile.Dispose();//释放资源
            Console.Read();
        }
    }
    回到顶部
    5.文件安全
    
    (1)ACL介绍
        ACL是存在于计算机中的一张表(访问控制表),它使操作系统明白每个用户对特定系统对象,例如文件目录或单个文件的存取权限。每个对象拥有一个在访问控制表中定义的安全属性。这张表对于每个系统用户有拥有一个访问权限。最一般的访问权限包括读文件(包括所有目录中的文件),写一个或多个文件和执行一个文件(如果它是一个可执行文件或者是程序的时候)。
    (2)读取文件的ACL
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file = new FileStream(@"E:Test.txt", FileMode.Open, FileAccess.Read);
            FileSecurity filesec = file.GetAccessControl();//得到文件访问控制属性
            //输出文件的访问控制项
            foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount)))
            {
                Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
            }
            file.Dispose();
            Console.Read();
        }
    }
    (3)读取文件夹的ACL
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo dir= new DirectoryInfo(@"E:学习笔记C#平台");
            DirectorySecurity filesec = dir.GetAccessControl();//得到文件访问控制属性
            //输出文件的访问控制项
            foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount)))
            {
                Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
            }
            Console.Read();
        }
    }
    (4)修改ACL
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file = new FileStream(@"E:Test.txt", FileMode.Open, FileAccess.Read);
            FileSecurity filesec = file.GetAccessControl();//得到文件访问控制属性
            Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
            FileSystemAccessRule rule = new FileSystemAccessRule(
                new NTAccount(@"CENTER-YFB-512LiZW"), //计算机账户名
                FileSystemRights.Delete, //操作权限
                AccessControlType.Allow);//能否访问受保护的对象
            filesec.AddAccessRule(rule);//增加ACL项
            Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
            filesec.RemoveAccessRule(rule);//移除ACL项
            Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
            file.Dispose();
            Console.Read();
        }
        //输出文件访问控制项
        static void Print(AuthorizationRuleCollection rules)
        {
            foreach (FileSystemAccessRule filerule in rules)
            {
                Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
            }
            Console.WriteLine("================================================");
        }
    }
    回到顶部
    6.读写注册表
    
    (1)注册表介绍
        Windows注册表是帮助Windows控制硬件、软件、用户环境和Windows界面的一套数据文件,运行regedit可以看到5个注册表配置单元(实际有7个):
            HKEY-CLASSES-ROOT:      文件关联和COM信息
            HKEY-CURRENT-USER:      用户轮廓
            HKEY-LOCAL-MACHINE:     本地机器系统全局配置子键
            HKEY-USERS:             已加载用户轮廓子键
            HKEY-CURRENT-CONFIG:    当前硬件配置
    (2).NET操作注册表的类
        在.NET中提供了Registry类、RegistryKey类来实现对注册表的操作。其中Registry类封装了注册表的七个基本主健:
            Registry.ClassesRoot    对应于HKEY_CLASSES_ROOT主键 
            Registry.CurrentUser    对应于HKEY_CURRENT_USER主键 
            Registry.LocalMachine   对应于 HKEY_LOCAL_MACHINE主键 
            Registry.User           对应于 HKEY_USER主键 
            Registry.CurrentConfig  对应于HEKY_CURRENT_CONFIG主键 
            Registry.DynDa          对应于HKEY_DYN_DATA主键 
            Registry.PerformanceData 对应于HKEY_PERFORMANCE_DATA主键
        RegistryKey类封装了对注册表的基本操作,包括读取,写入,删除。其中读取的主要函数有: 
            OpenSubKey()        主要是打开指定的子键。 
            GetSubKeyNames()    获得主键下面的所有子键的名称,它的返回值是一个字符串数组。 
            GetValueNames()     获得当前子键中的所有的键名称,它的返回值也是一个字符串数组。 
            GetValue()          指定键的键值。
        写入的函数:
          CreateSubKey()  增加一个子键 
          SetValue()      设置一个键的键值
        删除的函数:
          DeleteSubKey()      删除一个指定的子键。
          DeleteSubKeyTree()  删除该子键以及该子键以下的全部子键。
    (3)示例
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"SOFTWAREMicrosoftInternet ExplorerExtensions";
            RegistryKey pregkey = Registry.LocalMachine.OpenSubKey(path, true);//以只读方式
            if (pregkey != null)
            {
                Console.WriteLine(pregkey.Name + "--" + pregkey.SubKeyCount + "--" + pregkey.ValueCount);
                string preName = System.Guid.NewGuid().ToString();
                pregkey.CreateSubKey(preName);//增加一个子键
                RegistryKey new_pregkey = Registry.LocalMachine.OpenSubKey(path + @"" + preName, true);
                new_pregkey.SetValue("姓名", "李志伟");//设置一个键的键值
                new_pregkey.SetValue("键名", "值内容");//设置一个键的键值
                Console.WriteLine(pregkey.Name + "--" + pregkey.SubKeyCount + "--" + pregkey.ValueCount);
                pregkey.Close();
                new_pregkey.Close();
            }
            Console.Read();
        }
    }
    回到顶部
    7.读写独立的存储器
    
    (1)IsolatedStorageFile类
        使用IsolatedStorageFile类可以读写独立的存储器,独立的存储器可以看成一个虚拟磁盘,在其中可以保存只由创建他们的应用程序或其应用程序程序实例共享的数据项。
        独立的存储器的访问类型有两种(如下图):第一种是一个应用程序的多个实例在同一个独立存储器中工作,第二种是一个应用程序的多个实例在各自不同的独立存储器中工作。
    
    (2)示例
    class Program
    {
        static void Main(string[] args)
        {
            //写文件
            IsolatedStorageFileStream storStream = new IsolatedStorageFileStream(@"Test.txt", FileMode.Create, FileAccess.Write);
            string str = "测试数据:李志伟!ABCD";
            byte[] bs = Encoding.UTF8.GetBytes(str);
            storStream.Write(bs, 0, bs.Length);//写数据
            storStream.Dispose();
            //读文件
            IsolatedStorageFile storFile = IsolatedStorageFile.GetUserStoreForDomain();
            string[] files=storFile.GetFileNames(@"Test.txt");
            foreach (string t in files)
            {
                Console.WriteLine(t);
                storStream = new IsolatedStorageFileStream(t, FileMode.Open, FileAccess.Read);
                StreamReader sr=new StreamReader(storStream);
                Console.WriteLine("读取文件:"+sr.ReadToEnd());
                sr.Dispose();
                storFile.DeleteFile(t);//删除文件
            }
            storFile.Dispose();
            Console.WriteLine("OK!");
            Console.Read();
        }
    }
    -------------------------------------------------------------------------------------------------------------------------------
  • 相关阅读:
    fidller 打断点
    随笔
    HTML标签介绍
    补充9.27----9.28
    html5_______9.26
    9.14
    9.13笔记
    9.12笔记
    CSS样式的引用
    html5_______9.10
  • 原文地址:https://www.cnblogs.com/liyangLife/p/4797583.html
Copyright © 2011-2022 走看看