According to the MSDN documentation for FileStream.SafeFileHandle
:
The SafeFileHandle property automatically flushes the stream and sets the current stream position to 0. This allows the file to be moved or the stream position to be reset by another stream using the SafeFileHandle returned by this property.
However, my tests seem to indicate that the stream position is not changed.
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 stream position to 0, I'd have expected the second WriteLine() to print 0.
I have other tests where I actually use SafeFileHandle
with the Windows API ReadFile() and WriteFile() methods, and even then it doesn't appear to change the file pointer.
I have some code that uses SafeFileHandle
, so it's pretty important to me whether the stream position will be changed or not!
Have I misunderstood the documentation, or is it incorrect? Or does it change the stream position sometimes? (That would be a nightmare!)