C#__基本的读写文件方式

本文介绍了C#中的File类,包括如何使用静态方法进行文件读写操作,如ReadAllText读取文本文件,WriteAllText写入字符串,以及处理二进制文件。还展示了如何创建和覆盖文件,以及内存中读取文件的注意事项。
摘要由CSDN通过智能技术生成

// 代码+注释 

    class Program
    {
        /// <summary>
        /// Path类:
        /// 不能实例化;提供了一些静态方法,更容易对路径名执行操作;(有兴趣可以自行了解)
        /// 
        /// 读写文件:File类
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // ReadAllText(): 打开一个文本文件,读取文件的所有行,然后关闭该文件
            Console.WriteLine(File.ReadAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt"));
            /*
            这是一个文本文件
            小米南瓜是一种美味的食品
            欢迎大家前来品尝
            */

            // 打开一个文本文件,读取文件的所有行,然后关闭该文件
            string[] strArray = File.ReadAllLines(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt");
            foreach(string str in strArray)
            {
                Console.Write(str);
            }
            Console.WriteLine();
            // 这是一个文本文件小米南瓜是一种美味的食品欢迎大家前来品尝

            // 打开一个二进制文件(将文件转换为二进制文件),将文件的内容读入一个字节数组(0~255),然后关闭该文件
            Byte[] byteArray = File.ReadAllBytes(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt");
            int i = 0;
            while (i < byteArray.Length)
            {
                if (15 == i % 16)
                {
                    Console.WriteLine(byteArray[i]);
                }
                else
                {
                    Console.Write(byteArray[i] + " ");
                }
                i++;
            }
            /*
            239 187 191 232 191 153 230 152 175 228 184 128 228 184 170 230
            150 135 230 156 172 230 150 135 228 187 182 13 10 229 176 143
            231 177 179 229 141 151 231 147 156 230 152 175 228 184 128 231
            167 141 231 190 142 229 145 179 231 154 132 233 163 159 229 147
            129 13 10 230 172 162 232 191 142 229 164 167 229 174 182 229
            137 141 230 157 165 229 147 129 229 176 157
            */

            // 创建一个新文件,向其中写入指定的字符串,然后关闭文件。 如果目标文件已存在,则覆盖该文件。
            File.WriteAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt","Hello World!");
            Console.WriteLine(File.ReadAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt"));
            // Hello World!

            // 创建一个新文件,在其中写入指定的字节数组,然后关闭该文件(注意:每打印一行会换行,实际行数为输入的数组+1)
            File.WriteAllLines(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt", new string[]{ "1","2","3"});
            /*
             * 1
             * 2
             * 3
             
             */

            // Read:在内存中读文件,一般情况下不使用(不推荐)
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值