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.
Try using a "using":
using (FileStream fs = File.Create( filename ))
{
fs.Write( data, 0, data.Length );
}
Code looks OK ( using
would be better instead of .Close
).
Most likely your data
data.length == 0
) Your code works perfectly in my test environment so I have no idea what's going on there for you. Are the actual files you're writing to in the same directory? What I'm getting at is whether or not some security issue in your environment could be interfering with writing to files 2 and 3?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.