.net 添加文本到文本文件
StreamWriter没有Append方法,只能用seek设置位置,然后stream.WriteLine() 或stream.write(),这样会覆盖原来的文本。
找到需要添加行的位置,把要添加的行+原来后面所有的内容,再write()
void AppendText(FileInfo file)
{
FileStream fileStream = file.Open(FileMode.Open, FileAccess.ReadWrite);
int postion = 0;
StreamReader reader = new StreamReader(fileStream);
string content = reader.ReadToEnd();
StringBuilder builder = new StringBuilder();
fileStream.Seek(0, SeekOrigin.Begin);
postion = content.IndexOf("using");
string nextString = content.Substring(postion);
string x = "using System;\n"+nextString ;
fileStream.Seek(postion , SeekOrigin.Begin);
StreamWriter writer = new StreamWriter(fileStream);
writer.WriteLine(x);
writer.Flush();
fileStream.Close();
}