Reputation: 139
I have two filestreams which collects different information from different files:
FileStream dataStruc = new FileStream("c:\\temp\\dataStruc.txt", FileMode.Create, FileAccess.ReadWrite);
FileStream csvFile = new FileStream("c:\\temp\\" + fileName + ".txt", FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(csvFile);
StreamWriter swc = new StreamWriter(dataStruc);
when both streamwriters are used to get the same piece of information like shown below:
sw.WriteLine(sheet);
swc.WriteLine(sheet);
then sw
streamwriter has information from file. Have I set up my filestreams incorrectly?
Upvotes: 2
Views: 273
Reputation: 4632
I suppose that you have conflicting concurrent access to the file by both StreamWriters.
You open the streams with FileMode.Create
. See the MSDN documentation (highlights by me):
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This operation requires FileIOPermissionAccess.Write permission. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.
I am not sure if the second StreamWriter
, depending on the order of the initialization, overwrites the file of the first StreamWriter
or simply fails. Either way, they do try conflicting work.
Possible solutions:
FileMode
on the streams so that an existing file does not get overridden if possible. (See the documentation above.)Upvotes: 0
Reputation: 8821
Assuming you don't get any exceptions/errors and that basic stuff like the correct path for the csvFile
FileStream is verified and found to be correct: Try adding a Flush()
or propery closing the stream using Close()
. Even better: use a using
statement.
EDIT
After reading your question again: are you sure you just didn't switch the filestreams?
StreamWriter sw = new StreamWriter(csvFile);
StreamWriter swc = new StreamWriter(dataStruc);
as opposed to
StreamWriter sw = new StreamWriter(dataStruc);
StreamWriter swc = new StreamWriter(csvFile);
Your question and description is rather vague: "both streamwriters are used to get the same piece of information". How would stream writers be used to get information? Also: "sw streamwriter has information from file": could you be more specific? This doesn't make sense.
Whatever the case may be; use the debugger luke!
Upvotes: 2