Multiple File Names Created From One Streamwriter

G

Guest

I need the ability to create a series of individual files via one
Streamwriter (one at a time). Currently I have an application that is
writing out all of the data to one text file. The user has requested the
data is to be broken into individual files (could be from one to many depend
on the volume of data). This could lead to many separate files being
created. How do I write to a new file name using “StreamWriter sr =
File.CreateText(FileName)†?

Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

TC,

All you have to do is create a new FileStream, and then pass that to a
new StreamWriter.

Hope this helps.
 
B

Barry Kelly

TC said:
I need the ability to create a series of individual files via one
Streamwriter (one at a time). Currently I have an application that is
writing out all of the data to one text file. The user has requested the
data is to be broken into individual files (could be from one to many depend
on the volume of data). This could lead to many separate files being
created. How do I write to a new file name using “StreamWriter sr =
File.CreateText(FileName)†?

You need to flush the old stream writer when you're done with one file
and create a new instance via File.CreateText(string), as you indicate.

An idea: write a loop and name the files in sequence, for example:

---8<---
int fileNumber = 1;
while (!someWork.IsFinished)
{
using (TextWriter writer =
File.CreateText(string.Format("File{0}.txt", fileNumber)))
foreach (string someStuff in someWork)
writer.Write(someStuff);
++fileNumber;
}
--->8---

Without knowing more about what exactly your problem is, I think it is
difficult to help you.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top