简单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);
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐