c#替换原有⽂件内容
//实现替换原有⽂件内容
//Seek(0, SeekOrigin.Begin)将指针指向⽂件的开始,才能从⽂件的开头,但是此时如果新写⼊的流长度⼩于原有⽂件长度,则会保留原⽂件多余的信息using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.Write))
{
fileStream.Seek(0, SeekOrigin.Begin);
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write("this is clear file");
fileStream.Flush();
streamWriter.Close();
}
fileStream.Close();
}
//调⽤Stream的SetLength这个⽅法,将长度设为0,可以实现清空原有⽂件
using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.Write))
{
fileStream.SetLength(0);
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write("this is clear file");
fileStream.Flush();
streamWriter.Close();
}
fileStream.Close();
}truncated file
//如果⽂件已存在则清空,从Truncate打开的⽂件中读取将引发异常
using (FileStream fileStream = new FileStream(file, FileMode.Truncate, FileAccess.Write, FileShare.Write))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write("this is");
fileStream.Flush();
streamWriter.Close();
}
fileStream.Close();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。