Am I missing something? That StreamWriter does nothing. You write to it, then Flush, Close and Dispose. Also, where does the context.Files come from? Your question mentions Entities which leads me to think context is an ObjectContext and File is a Table in your Database.
So what does this code do? It iterates through the File table records, writes a SQL statement that inserts the already existing records into the same table to a Stream, then Disposes of the Stream the end.
So what is
context
exactly and what are you trying to achieve? If I read this I cannot conclude, but that this code does nothing except, throw Exceptions. Could you mention the Exception too?
Edit; OP has edited his question.
The following code will create a new .txt file on the C:\ drive. It's initial text will be "Test", but every time the code passes this again "Test" will be appended on a new line.
string s = "Test" + Environment.NewLine;
using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\MyFile.txt", System.IO.FileMode.Append)) {
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fs)) {
writer.Write(s);
writer.Flush();
fs.Flush();
writer.Close();
fs.Close();
}
}
I suggest you build the String in your loop and then use this code to append it to your file.
Hope this is what you are looking for/what you need.