How to Write to a file using StreamWriter?

2020-07-11 07:02发布

in my Wpf app I'm using a class Person (that is a base class), and that contains a virtual method SaveData(), and other class Client that inherits from Person. How to override method SaveData() and keeping data from base?

Class Person

public virtual void SaveData()
{
   string arqName = string.Format("Person{0}" + ".txt", Id);
   StreamWriter file = new StreamWriter(arqNome);
   file.WriteLine("ID: " + Id);
   file.WriteLine("DOB: " + dOB);
   file.WriteLine("Name: " + name);
   file.WriteLine("Age: " + age);
   file.Flush();
   file.Close();     
}

Class Client

public override void SaveData()
{
   base.SaveData();
   string arqName = string.Format("Person{0}" + ".txt", Id);
   StreamWriter file = new StreamWriter(arqNome);
   file.WriteLine("Cod: " + cod);
   file.WriteLine("Credits: " + credits);
   file.Flush();
   file.Close();
}

The override method in Client is indeed override others data as Name, Age, DOB... I need to mantains both in same file.

3条回答
▲ chillily
2楼-- · 2020-07-11 07:25

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);
}
查看更多
对你真心纯属浪费
3楼-- · 2020-07-11 07:40

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);
查看更多
仙女界的扛把子
4楼-- · 2020-07-11 07:47

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.

查看更多
登录 后发表回答