I have a list of file names that I will be creating and writing to. I have a foreach loop going through them all something like this
void WriteFiles(byte[] data)
{
foreach (string fileName in fileNames)//fileNames is my List<string>
{
FileStream fs = File.Create(fileName)
fs.Write(data, 0, data.Length);
fs.Close();
}
}
Let's say my list of files is 1.txt, 2.txt, and 3.txt The strange thing is, 1.txt, 2.txt, and 3.txt are all created. but the data is just written 3 times to 1.txt, and 2.txt and 3.txt are empty. I have double checked in the debugger, and fileName is different each time it loops. I have written many programs that read from and write to files, but I have never encountered any behavior like this. I'm very confused.
EDIT
Perhaps this will make more sense. This is actual code that I have run and produced the problem with, copied and pasted straight from Visual Studio.
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static List<string> fileNames = new List<string>();
static void Main()
{
Directory.CreateDirectory("C:\\textfiles");
fileNames.AddRange(new string[] { "1.txt", "2.txt", "3.txt" });
WriteFiles();
}
static void WriteFiles()
{
foreach (string fileName in fileNames)
{
using (StreamWriter sw = new StreamWriter(File.Create("c:\\textfiles\\" + fileName)))
{
sw.Write("This is my text");
}
}
}
}
}
After executing this, I now have 3 text files (1.txt, 2.txt, 3.txt) in the folder C:\textfiles, none of which existed before.
When I open the files in notepad here's what I've got
1.txt - "This is my textThis is my textThis is my text"
2.txt - nothing
3.txt - nothing
WTF??? This doesn't make sense.