except for the comments here ( MemoryStream disables reading when returned ), I haven't found a good answer to my concerns about leaving a StreamWriter open. I would like to return a MemoryStream (open) that is written by a StreamWriter in a safe and clean way.
Let me give a rather simple example. I would like to use the Method GetMemoryStream() like this:
String[] content = { "large", "string", "array", "test" };
MemoryStream ms = GetMemoryStream(content);
//byte[] array = ms.ToArray(); //still works after stream is closed but I want an open and working stream.
using (FileStream fs = new FileStream(@"C:\Test.txt", FileMode.Create, FileAccess.ReadWrite))
{
//fs.Write(array, 0, array.Length);
ms.WriteTo(fs);
}
ms.Dispose();
Now here are two ways I found to do so:
Copy the MemoryStream
public static MemoryStream GetMemoryStream(String[] content) { MemoryStream result = new MemoryStream(); using (MemoryStream ms = new MemoryStream()) using (StreamWriter sw = new StreamWriter(ms)) { foreach (String s in content) sw.WriteLine(s); sw.Flush(); ms.CopyTo(result); } return result; }
This aproach looks like a workaround to me. It seems (correct me if I'm wrong) to need twice as much memory and more time. Then I read about the next aproach:
Leave the StreamWriter Open (>=.Net 4.5)
public static MemoryStream GetMemoryStream(String[] content) { MemoryStream ms = new MemoryStream(); using (StreamWriter sw = new StreamWriter(ms, Encoding.Default, 1024, true)) { foreach (String s in content) sw.WriteLine(s); } return ms; }
But I have concerns with that aproach:
What happens to the StreamWriter when I leave the scope?
Is the data still referenced/held by that StreamWriter object?
Will it be garbage-collected? Maybe even before I get to use the MemoryStream in the calling scope?
Is it still "connected" to the MemoryStream, and maybe disposed when I dispose ms?
To sum it up: Is the second aproach going to cause any trouble?
Thanks in advance