C#文件操作

C#文件操作

这里主要介绍两种文件操作的方法
第一种方式
这种方式比较繁琐,如果忘记清除缓存数据流那么文件数据是存不进去的,就比较麻烦

C#文件操作
 //写入数据到文件
            string filePath = "filetest.txt";
            FileStream file = null;
            if (File.Exists(filePath))
            {
                //存在就打开文件
                file = File.Open(filePath, FileMode.Open);
            }
            else {
                //不存在就创建文件
                file = File.Create(filePath);
            }
            //实例化字符串缓存区对象,并指定文件文件流对象
            StreamWriter write = new StreamWriter(file);
            //写数据到文件(通过Stream方式,把字符串写入到流)
            //还有WriteLine("你好中国!")方法,写完一行后自动换行
            write.Write("你好中国!\nHello China!");
            //清除缓存数据流
            write.Flush();
            //关闭当前的StreamWrite对象和基础流
            write.Close();
            //关闭文件
            file.Close();

 //从文件中读取数据
            string filePath = "filetest.txt";
            FileStream file = null;
            if (File.Exists(filePath))
            {
                //存在就打开文件
                file = File.Open(filePath, FileMode.Open);
            }
            else
            {
                //不存在文件就抛出异常
                 throw new Exception("file is not exists");
            }
            //读取文件
            StreamReader read = new StreamReader(file);
            //读取一行数据
            string str = read.ReadLine();
            //移动光标到文件头
            file.Seek(0, SeekOrigin.Begin);
            //读取文件的全部数据
            string strall =  read.ReadToEnd();
            //丢弃缓存数据
            read.DiscardBufferedData();
            //关闭文件
            read.Close();

第二种方式
这种方式比较简洁,易懂,忘了点啥好像也没多大关系,建议使用

			string path = "filetest.txt";
            //File.OpenWrite() 打开一个已经存在的文件或者创建一个新文件用来写数据
            //File.OpenRead() 打开一个已经存在的文件用来读取数据
            //使用using()这种方式读写文件,清除缓存数据流或关闭文件将由系统自动完成
            using (FileStream file = File.OpenWrite(path)) {
                //你需要存入的信息
                string savestr = "你好中国!\nHello China!";
                //将字符串转为字节数组
                byte[] data = Encoding.UTF8.GetBytes(savestr);
                //写入数据到文件
                file.Write(data, 0, data.Length);
            }
            using (FileStream file = File.OpenRead(path)) {
                //获取文件的长度
                long filelength = file.Seek(0, SeekOrigin.End);
                //获取长度之后,要把文件光标偏移到文件头
                file.Seek(0, SeekOrigin.Begin);
                //创建字节数组
                byte[] getbytes = new byte[filelength];
                //将读取文件长度的字节数据到字节数组中
                int count = file.Read(getbytes, 0, (int)filelength);
                //将字节数组转为字符串
                string getstr = Encoding.UTF8.GetString(getbytes);
            }

如果对文件光标偏移不是很清楚的可以看下图
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值