How to Write to a file using StreamWriter?

只愿长相守 提交于 2019-12-04 06:00:35

StreamWriter is stream decorator, so you better instantiate FileStream and pass it to the StreamWriter constructor. Thus you can customize it. Append mode opens file and moves pointer to the end of file, so the next thing you write will be appended. And use using directive insted of explicitly calling Close():
Person class SaveData():

using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.OpenOrCreate))
using (var streamWriter = new StreamWriter(fileStream))
{
    streamWriter.WriteLine("ID: " + Id);
    streamWriter.WriteLine("DOB: " + dOB);
    streamWriter.WriteLine("Name: " + name);
    streamWriter.WriteLine("Age: " + age);
}

Client class SaveData():

base.SaveData();
using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.Append))
using (var streamWriter = new StreamWriter(fileStream))
{
    streamWriter.WriteLine("Cod: " + cod);
    streamWriter.WriteLine("Credits: " + credits);
}

You should split it into 2 methods: SaveData() and WriteData(StreamWriter file). SaveData creates the stream and then calls WriteData. Then you override only the WriteDate method, calling the base.

AlexDev's answer is correct. But if you can't alter Person code (and given that you store data per file) you can use 'append' flag to add data into existed file. But it's not the best idea:

StreamWriter file = new StreamWriter(arqNome, append: true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!