Given this example code:
1: using (StreamWriter sw = new StreamWriter(@"C:\file.txt"))
2: {
3: sw.WriteLine(great_string);
4: }
5:
6: using (StreamReader sr = new StreamReader(@"C:\file.txt"))
7: {
8: sr.ReadToEnd();
9: }
Is it possible that the great_string written on line 3 would not be present in C:\file.txt when StreamReader.ReadToEnd is called on line 8? It seems to me that it would be possible, because your average CPU works much faster than your average HDD, but I’ve been testing this today, and so far the string written on line 3 is always present when I read the file on line 8. I’m thinking that maybe the using statement won’t close the stream until all of the data is written to / read from the file, thus preventing the kind of situation that I’m asking about.
I’ve been reading about the StreamWriter.Close method on MSDN, and it states the following:
You must call Close to ensure that all data is correctly written out to the underlying stream.
But it doesn’t say WHEN the data will be written out to the underlying stream.
Thanks in advance for any info on this subject. I did search for answers to this question, but I didn’t find anything…I didn’t really know what terms to search for.
The data might not be physically present on the HDD after calling Close but the system (the windows Kernel) will give the appearance that it is. And all that matters is the appearance.
If you read from the file just written Windows will either ask the HDD or serve from cache.
If this was not the case it would be hard to write reliable programs because the order of effects could change arbitrarily across functions and even processes. It would be chaos. So the system guarantees sequential consistency.
If you think about it: If this serialization property was not present a file could have multiple contents at the same time! Read it the first time and you see the old contents. Read it again and you suddenly see changes appear. This kind of behavior is not possible, fortunately.