c#--文件读写、删除及追加内容的几种方法

简单string的读写

1.写入:

StreamWriter sw = File.AppendText(txtPath); //保存到指定路径
sw.Write(txt);
sw.Flush();
sw.Close();

2.读内容:

 string strContent = File.ReadAllText(path);

3.追加内容:

无文件会自动生成文件

using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
   //获得字节数组
   byte[] data = System.Text.Encoding.Default.GetBytes(info);//info为要追加的数据
   //设定书写的开始位置为文件的末尾 
   fs.Position = fs.Length;
   //开始写入
   fs.Write(data, 0, data.Length);
   //清空缓冲区、关闭流
   fs.Flush();
}

4.修改某一行并追加内容

string[] array = File.ReadAllLines(path3);
array[0] = count.ToString(); 
List<string> newTxtList = new List<string>();
newTxtList.AddRange(array);
newTxtList.Add(timeSpan.ToString());
File.WriteAllLines(path3, newTxtList);

二进制读写:

1.读

 using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
 {
     int size = (int)fs.Length;
     BinaryReader br = new BinaryReader(fs);
     var bytes = br.ReadBytes(size);
     br.Close();
 }

2.写

using (FileStream fs2 = new FileStream(path2, FileMode.Create, FileAccess.Write))//追加内容FileMode.Create改为FileMode.Append
{
     BinaryWriter bw = new BinaryWriter(fs2);
     bw.Write(newBytes);
     bw.Close();
 }

文件删除

File.Delete(oldPath);
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yyuanyuxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值