1

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.

  • 3
    Is the code you posted verbatim or simplified? – Kennet Belenky Apr 17 '12 at 00:35
  • 3
    You might want to use `File.WriteAllBytes()`, because it's simpler. But there doesn't seem to be anything wrong in the code you posted. Could you try to simplify your code as much as you can and then post it here? – svick Apr 17 '12 at 00:37
  • 3
    Where are you getting `filenames`? From LINQ? Check that you are not introducing a variable you are capturing the last used value of. Read http://stackoverflow.com/questions/190227/building-a-linq-query-programatically-without-local-variables-tricking-me – Dour High Arch Apr 17 '12 at 00:40
  • I agree, I smell a closure... – Michael Edenfield Apr 17 '12 at 00:56
  • I'm definitely getting the right values for file names. The fact that all 3 files are created tells me that. I even chacked with a breakpoint. The first time through the loop, fileName is 1.txt, Second time 2.txt, and third time, 3.txt. The FileStreams are creating the correct files, but always write the data to 1.txt. It really makes no sense at all. – Pearce Yaussy Apr 17 '12 at 01:06
  • No, I'm not getting then from LINQ, In this simplified version of the program I just did List fileNames = new List() and then added the file names one by one like fileNames.Add("1.txt"). – Pearce Yaussy Apr 17 '12 at 01:09
  • This makes little sense from the snippet. Writing byte[] to .txt files makes no sense either. Post real code and accurate descriptions of your problem. – Hans Passant Apr 17 '12 at 01:35
  • I can't replicate your problem with the code you provided: it works fine for me. – svick Apr 17 '12 at 10:01

3 Answers3

0

Try using a "using":

using (FileStream fs = File.Create( filename ))
{
    fs.Write( data, 0, data.Length );
}
Joel Lucsy
  • 8,520
  • 1
  • 29
  • 35
0

Code looks OK (using would be better instead of .Close).

Most likely your data

  • empty altogether (data.length == 0)
  • does not represent text that can be displayed (if you write something like [0,0,0] to a text file it will display nothing.
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
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?