Reputation:
Hey guys I need a tad bit of help. I need my streamwriter to right out the file names i get from a Directory.Getfiles call
string lines = (listBox1.Items.ToString());
string sourcefolder1 = textBox1.Text;
string destinationfolder = (@"C:\annqcfiles");
string[] files = Directory.GetFiles(sourcefolder1, lines + "*.ann");
foreach (string listBoxItem in listBox1.Items)
{
Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt");
StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt");
}
It creates the files perfectly it just doesnt add any content to the files. All i really want is the filename of the files it finds in the getfiles result.
Thanks in for any advice.
Upvotes: 0
Views: 617
Reputation: 2857
You have to close your StreamWriter.
Or wrap your StreamWriter in a using statement, this will dispose and close your stream automatically.
The reason behind this is that your stream will keep your output in a buffer and only write it to a file when:
- a certain threshold is reached
- you call flush on it explicitly
- close or dispose the stream
Upvotes: 0
Reputation: 27509
Two things. Firstly you actually need to write the data to the StreamWriter, and secondly you need to make sure you close the StreamWriter so it actually gets flushed to the file.
Try this:
foreach (string listBoxItem in listBox1.Items)
{
String[] filesInFolder Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt");
using(StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
{
foreach(string filename in filesInFolder)
{
output.Write(filename);
}
}
}
The using
statement ensures that the StreamWriter is closed when the execution passes out of the using block.
Alternatively, if this is all you are writing to the file, you could take a look at the Files.WriteAllLines(...) method.
Upvotes: 1
Reputation: 11920
You should wrap your streamwriter in a using statement, which will flush and close the streamwriter
using(StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
{
//Any code that writes in output
}
Upvotes: 0
Reputation: 59553
foreach (string listBoxItem in listBox1.Items)
{
using (StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
{
foreach (string fileName in Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt"))
{
output.WriteLine(fileName);
}
}
}
Upvotes: 5
Reputation: 1064204
Since GetFiles
returns a string[]
, don't use StreamWriter
at all - just
File.WriteAllLines(path, files);
Where files
is the string[]
of paths to write, and path
is the destination file.
Upvotes: 2