Does FileStream.SafeFileHandle * really set the current stream position to 0?

According to MSDN documentation for FileStream.SafeFileHandle :

The SafeFileHandle property automatically clears the stream and sets the current position of the stream to 0. This allows you to move the file or stream position reset to another stream using the SafeFileHandle returned by this property.

However, my tests show that the position of the stream does not change.

Consider the following code:

 using System; using System.IO; namespace Demo { internal static class Program { public static void Main() { Directory.CreateDirectory("C:\\TEST"); var buffer = new byte[1024]; using (var file = new FileStream("C:\\TEST\\TEST.BIN", FileMode.Create)) { file.Write(buffer, 0, buffer.Length); Console.WriteLine(file.Position); // Prints 1024 var dummy = file.SafeFileHandle; // dummy.Dispose(); // Uncommenting this line will make the next line throw. Console.WriteLine(file.Position); // Still prints 1024! } } } } 

If accessing SafeFileHandle really did reset the current position of the stream to 0, I would expect the second WriteLine () to print 0.

I have other tests in which I actually use SafeFileHandle with the Windows API ReadFile () and WriteFile () methods, and even then it will not change the file pointer.

I have a code that uses SafeFileHandle , so it is very important for me whether the position of the stream will change or not!

Am I misunderstood the documentation, or is it wrong? Or sometimes does it change the position of the flow? (That would be a nightmare!)

+4
source share
1 answer

I think the documentation actually talks about the input and output buffers used by FileStream ( FileStream buffers input and output for better performance. ).

If you use the source source of the .NET library, you can see that the SafeFileHandle property actually flushes all buffers (i.e. caches) and flushes their positions to zero. It does not concern a variable that contains information on how far the file has actually been read (or written). The Position property, in turn, always uses this variable (plus buffer / cache offsets) to return its value.

The important part seems to be this:

This allows you to move the file or position of the reset thread to another thread using the SafeFileHandle returned by this property.

Basically, SafeFileHandle guarantees you that you can use the return value (like SetFilePointer ) to access the file and not have problems with (possible) caching of the FileStream instance.

+5
source

All Articles