当前位置: 移动技术网 > IT编程>开发语言>c# > C# IO流与文件读写学习笔记

C# IO流与文件读写学习笔记

2020年01月02日  | 移动技术网IT编程  | 我要评论

    本笔记摘抄自:https://www.cnblogs.com/liyanglife/p/4797583.html,记录一下学习过程以备后续查用。

    一、文件系统

    1.1文件系统类的介绍

    文件操作类大都在system.io命名空间里,filesysteminfo类是所有文件系统类的基类。fileinfo与file表示文件系统中的文件,directoryinfo与directory

表示文件系统中的文件夹,path表示文件系统中的路径,driveinfo提供对有关驱动器信息的访问。

    注意,xxxinfo与xxx类的区别是:xxx是静态类,xxxinfo类可以实例化。还有个较为特殊的类system.marshalbyrefobject允许在支持远程处理的

应用程序中跨应用程序域边界访问对象。

    1.2fileinfo与file类

    class program
    {
        static void main(string[] args)
        {
            #region fileinfo与file类
            //创建文件
            fileinfo file = new fileinfo(@"e:\学习笔记\c#\test.txt");
            filestream fs = file.create();
            //关闭文件流,这个很重要。
            fs.close();
            console.writeline("创建时间:" + file.creationtime);
            console.writeline("文件路径:" + file.directoryname);
            //打开追加流
            streamwriter sw = file.appendtext();
            //追加数据
            sw.write("科比·布莱恩特");
            //释放资源,关闭文件。
            sw.dispose();
            //移动
            file.move(file.fullname, @"e:\学习笔记\test.txt");
            console.writeline("文件创建并操作完成。");
            console.read();
            #endregion
        }
    }

    运行结果如下:

    1.3directoryinfo与directory类

    class program
    {
        static void main(string[] args)
        {
            #region fileinfo与file类
            ////创建文件
            //fileinfo file = new fileinfo(@"e:\学习笔记\c#\test.txt");
            //filestream fs = file.create();
            ////关闭文件流,这个很重要。
            //fs.close();
            //console.writeline("创建时间:" + file.creationtime);
            //console.writeline("文件路径:" + file.directoryname);
            ////打开追加流
            //streamwriter sw = file.appendtext();
            ////追加数据
            //sw.write("科比·布莱恩特");
            ////释放资源,关闭文件。
            //sw.dispose();
            ////移动
            //file.move(file.fullname, @"e:\学习笔记\test.txt");
            //console.writeline("文件创建并操作完成。");
            //console.read();
            #endregion

            #region directoryinfo与directory类
            //创建文件夹
            directoryinfo directory = new directoryinfo(@"e:\学习笔记\c#\test");
            directory.create();
            console.writeline("父文件夹:" + directory.parent.fullname);
            //输出父目录下的所有文件夹与文件
            filesysteminfo[] infos = directory.parent.getfilesysteminfos();
            foreach (filesysteminfo info in infos)
            {
                console.writeline(info.name);
            }
            //删除文件夹
            directory.delete(directory.fullname);
            console.writeline("文件夹创建并操作完成。");
            console.read();
            #endregion
        }
    }

    运行结果如下:

    1.4path类

    class program
    {
        static void main(string[] args)
        {
            #region path类
            //连接
            console.writeline(path.combine(@"e:\学习笔记\c#", @"test.txt"));
            console.writeline("平台特定的字符:" + path.directoryseparatorchar);
            console.writeline("平台特定的替换字符:" + path.altdirectoryseparatorchar);
            console.read();
            #endregion
        }
    }

    运行结果如下:

    1.5driveinfo类

    class program
    {
        static void main(string[] args)
        {
            #region driveinfo类
            driveinfo[] drives = driveinfo.getdrives();
            foreach (driveinfo drive in drives)
            {
                if (drive.isready)
                {
                    console.writeline("驱动器名称:" + drive.name);
                    console.writeline("驱动器类型:" + drive.driveformat);
                    console.writeline("总容量:" + drive.totalfreespace);
                    console.writeline("可用容量:" + drive.availablefreespace + "\n");


                }
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

    二、文件操作

    2.1文件的移动、复制、删除

    class program
    {
        static void main(string[] args)
        {
            #region 文件的移动、复制、删除
            string path = @"e:\学习笔记\test.txt";

            file.writealltext(path, "测试数据");
            console.writeline("文件已写入。");

            file.move(path, @"e:\学习笔记\c#\test.txt");
            console.writeline("文件已移动。");

            file.copy(@"e:\学习笔记\c#\test.txt", path);
            console.writeline("文件已复制。");

            file.delete(@"e:\学习笔记\c#\test.txt");
            console.writeline("文件已删除。");

            console.read();
            #endregion
        }
    }

    2.2判断路径是文件还是文件夹

    class program
    {
        static void main(string[] args)
        {
            #region 判断路径是文件还是文件夹
            isfile(@"e:\学习笔记\test.txt");
            isfile(@"e:\学习笔记\");
            isfile(@"e:\学习笔记\xxx");
            console.read();
            #endregion
        }

        /// <summary>
        /// 判断路径是文件还是文件夹
        /// </summary>
        /// <param name="path"></param>
        static void isfile(string path)
        {
            if (file.exists(path))
            {
                console.writeline("这是个文件。");
            }
            else if (directory.exists(path))
            {
                console.writeline("这是个文件夹。");
            }
            else
            {
                console.writeline("路径不存在。");
            }
        }
    }

    运行结果如下:

    三、文件读写与数据流

    3.1文件读取

    class program
    {
        static void main(string[] args)
        {
            #region 文件读取
            string path = @"e:\学习笔记\test.txt";
            byte[] bytes = file.readallbytes(path);
            console.writeline("readallbytes读二进制:");
            foreach (byte b in bytes)
            {
                console.write((char)b);
            }
            console.writeline(environment.newline);

            string[] strs = file.readalllines(path, encoding.utf8);
            console.writeline("readalllines读所有行:");
            foreach (string s in strs)
            {
                console.writeline(s + "\n");
            }

            string str = file.readalltext(path, encoding.utf8);
            console.writeline("readalltext读所有行:\n" + str);
            console.read();
            #endregion
        }
    }

   运行结果如下:

    3.2文件写入

    class program
    {
        static void main(string[] args)
        {
            #region 文件写入
            string path = @"e:\学习笔记\test.txt";
            file.writeallbytes(path, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });  //写入二进制
            console.writeline("writeallbytes写入二进制成功。");

            string[] array = { "123", "456", "789" };
            file.writealllines(path, array, encoding.utf8);                         //写入所有行
            console.writeline("writealllines写入所有行成功。");

            file.writealltext(path, "hello world", encoding.utf8);                  //写入字符串
            console.writeline("writealltext写入字符串成功。\n");

            console.read();
            #endregion
        }
    }

    3.3数据流

    filestream:文件流,可以读写二进制文件。

    streamreader:流读取器,使其以一种特定的编码从字节流中读取字符。

    streamwriter:流写入器,使其以一种特定的编码向流中写入字符。

    bufferedstream:缓冲流,给另一流上的读写操作添加一个缓冲层。

    3.3.1使用filestream读写二进制文件

    class program
    {
        static void main(string[] args)
        {
            #region 使用filestream读写二进制文件
            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("写入数据成功!!!");
            //以读文件的方式打开文件
            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();
            #endregion
        }
    }

    运行结果如下:

    3.3.2streamwriter与streamreader

    使用streamwriterstreamreader就不用担心文本文件的编码方式,所以它们很适合读写文本文件。

    class program
    {
        static void main(string[] args)
        {
            #region streamwriter与streamreader
            string path = @"e:\学习笔记\c#\test1.txt";
            //以写文件的方式创建文件
            filestream file = new filestream(path, filemode.create, fileaccess.write);
            streamwriter sw = new streamwriter(file);
            sw.writeline("科比·布莱恩特");
            sw.dispose();
            console.writeline("写入数据成功!!!");
            //以读文件的方式打开文件
            file = new filestream(path, filemode.open, fileaccess.read);
            streamreader sr = new streamreader(file);
            console.writeline("读取数据:" + sr.readtoend());
            sr.dispose();
            console.read();
            #endregion
        }
    }

    运行结果如下:

   四、内存映射文件

    memorymappedfile类(.net4新增):

    应用程序需要频繁地或随机地访问文件时,最好使用memorymappedfile类(映射内存的文件)。使用这种方式允许把文件的一部分或者全部加载到一段

虚拟内存上,这些文件内容会显示给应用程序,就好像这个文件包含在应用程序的主内存中一样。

    class program
    {
        static void main(string[] args)
        {
            #region 内存映射文件
            memorymappedfile mmfile = memorymappedfile.createfromfile(@"e:\学习笔记\c#\test2.txt", filemode.openorcreate, "mapname", 1024 * 1024);
            //内存映射文件的视图
            //或使用数据流操作内存文件memorymappedviewstream stream = mmfile.createviewstream();
            memorymappedviewaccessor mmviewaccessor = mmfile.createviewaccessor();
            string str = "科比·布莱恩特";
            int length = encoding.utf8.getbytecount(str);
            //写入数据
            mmviewaccessor.writearray<byte>(0, encoding.utf8.getbytes(str), 0, length);
            byte[] bytes = new byte[length];
            mmviewaccessor.readarray<byte>(0, bytes, 0, bytes.length);
            console.writeline(encoding.utf8.getstring(bytes));
            //释放资源
            mmfile.dispose();
            console.read();
            #endregion
        }
    }

    运行结果如下:

    五、文件安全

    5.1acl介绍

    acl是存在于计算机中的一张表(访问控制表),它使操作系统明白每个用户对特定系统对象--例如文件目录或单个文件的存取权限,每个对象拥有一个在

访问控制表中定义的安全属性。每个系统用户对于这张表拥有一个访问权限,最一般的访问权限包括读文件(包括所有目录中的文件)、写一个或多个文件

和执行一个文件(如果它是一个可执行文件或者是程序的时候)。

    5.2读取文件的acl

    class program
    {
        static void main(string[] args)
        {
            #region 读取文件的acl
            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();
            #endregion
        }
    }

    运行结果如下:

    5.3读取文件夹的acl

    class program
    {
        static void main(string[] args)
        {
            #region 读取文件夹的acl
            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();
            #endregion
        }
    }

    运行结果如下:

    5.4修改acl

    class program
    {
        static void main(string[] args)
        {
            #region 修改acl
            filestream file = new filestream(@"e:\学习笔记\test.txt", filemode.open, fileaccess.read);
            //得到文件访问控制属性
            filesecurity filesec = file.getaccesscontrol();
            //输出文件访问控制项
            printacl(filesec.getaccessrules(true, true, typeof(ntaccount)));
            filesystemaccessrule rule = new filesystemaccessrule
                (
                    new ntaccount(@"atomystudio\administrator"),                //计算机账户名
                    filesystemrights.delete,                                    //操作权限
                    accesscontroltype.allow                                     //能否访问受保护的对象
                );
            filesec.addaccessrule(rule);                                        //增加acl项
            printacl(filesec.getaccessrules(true, true, typeof(ntaccount)));    //输出文件访问控制项
            filesec.removeaccessrule(rule);                                     //移除acl项
            printacl(filesec.getaccessrules(true, true, typeof(ntaccount)));    //输出文件访问控制项
            file.dispose();
            console.read();
            #endregion
        }
    }

    运行结果如下:

    六、读写注册表

    6.1注册表介绍

    windows注册表是帮助windows控制硬件、软件、用户环境和windows界面的一套数据文件,运行regedit可以看到有5个注册表配置单元(实际有7个):

    hkey-classes-root: 文件关联和com信息

    hkey-current-user: 用户轮廓

    hkey-local-machine: 本地机器系统全局配置子键

    hkey-users: 已加载用户轮廓子键

    hkey-current-config: 当前硬件配置

    6.2.net操作注册表的类

    在.net中提供了registry类、registrykey类来实现对注册表的操作。

    6.2.1registry类

    封装了注册表的七个基本主键:

    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主键

    6.2.2registrykey类

    封装了对注册表的基本操作,包括读取、写入,删除。

    1)读取的函数:

    opensubkey() 主要是打开指定的子键

    getsubkeynames() 获得主键下面的所有子键的名称,它的返回值是一个字符串数组。

    getvaluenames() 获得当前子键中的所有的键名称,它的返回值也是一个字符串数组。

    getvalue() 指定键的键值。

    2)写入的函数:

    createsubkey() 增加一个子键

    setvalue() 设置一个键的键值

    3)删除的函数:

    deletesubkey() 删除一个指定的子键

    deletesubkeytree() 删除该子键以及该子键以下的全部子键

    6.3示例

    class program
    {
        static void main(string[] args)
        {
            #region 读写注册表
            string path = @"software\microsoft\internet explorer\extension compatibility";
            //以只读方式
            registrykey registrykey = registry.localmachine.opensubkey(path, true);
            if (registrykey != null)
            {
                console.writeline(registrykey.name + "--" + registrykey.subkeycount + "--" + registrykey.valuecount);
                string subregistrykey = guid.newguid().tostring();
                //增加一个子键
                registrykey.createsubkey(subregistrykey);
                registrykey newregistrykey = registry.localmachine.opensubkey(path + @"\" + subregistrykey, true);
                //设置一个键的键值
                newregistrykey.setvalue("姓名", "科比");
                //设置一个键的键值
                newregistrykey.setvalue("键名", "布莱恩特");
                console.writeline(registrykey.name + "--" + registrykey.subkeycount + "--" + registrykey.valuecount);
                registrykey.close();
                newregistrykey.close();
            }
            console.read();
            #endregion
        }
    }

    运行结果生成值为:

    七、读写独立的存储器

    7.1isolatedstoragefile类

    使用isolatedstoragefile类可以读写独立的存储器。

    独立的存储器可以看成一个虚拟磁盘,在其中可以保存只由创建他们的应用程序或其应用程序实例共享的数据项。

    独立的存储器的访问类型有两种:第一种是一个应用程序的多个实例在同一个独立存储器中工作,第二种是一个应用程序的多个实例在各自不同的独立存

储器中工作。

    7.2示例

    class program
    {
        static void main(string[] args)
        {
            #region 读写独立的存储器
            //写文件
            isolatedstoragefilestream filestream = new isolatedstoragefilestream(@"test.txt", filemode.create, fileaccess.write);
            string str = "科比·布莱恩特";
            byte[] bytes = encoding.utf8.getbytes(str);
            //写数据
            filestream.write(bytes, 0, bytes.length);
            filestream.dispose();
            //读文件
            isolatedstoragefile file = isolatedstoragefile.getuserstorefordomain();
            string[] filenames = file.getfilenames(@"test.txt");
            foreach (string filename in filenames)
            {
                console.writeline(filename);
                filestream = new isolatedstoragefilestream(filename, filemode.open, fileaccess.read);
                streamreader sr = new streamreader(filestream);
                console.writeline("读取文件:" + sr.readtoend());
                sr.dispose();
                //删除文件
                file.deletefile(filename);
            }
            file.dispose();
            console.writeline("ok!");
            console.read();
            #endregion
        }
    }

    运行结果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网