Netherwire
Netherwire

Reputation: 2787

Is it possible for StreamWriter to open different files?

I has initialized the StreamWriter instance and associated it with "MyFile.txt"

System.IO.StreamWriter sw = new StreamWriter("MyFile.txt");

So now I can write data into this file

sw.Write("Hello, world!");

Is it possible to open another file with the same StreamWriter (sw) instance some way like:

sw.Reopen("MySecondFile");

Or not/it's senseless?

Upvotes: 3

Views: 383

Answers (3)

knittl
knittl

Reputation: 265131

Simply create a new StreamWriter instance:

StreamWriter sw = new StreamWriter("MyFile.txt");
sw.Write("Hello world!");
sw.Close();
sw = new StreamWriter("SecondFile");
sw.Write("Goodbye world!");

So, in a way it's senseless, since you can create new instances cheaply. The old instance will eventually get garbage collected automatically, so you don't have to worry about memory leaks.

Upvotes: -1

demo.b
demo.b

Reputation: 3439

Using StreamWriter you need to create a new instance to write to another file.

Upvotes: 0

Paul D'Ambra
Paul D'Ambra

Reputation: 7814

Looking at the documentation on StreamWriter. The only way to associate the StreamWriter with a file is in the constructor.

So, no, it's not possible to re-use an instance with a second file

Upvotes: 3

Related Questions