Domanda

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!)

È stato utile?

Soluzione

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

If you use the .NET library reference source, you can see that the SafeFileHandle property actually flushes all buffers (i.e. caches) and resets their positions back to zero. It doesn't touch the variable that holds the information about how far the file has really been read (or written). The Position property in turn, always uses that variable (plus the buffer /cache offsets) to return it's value.

The important part seems to be this:

This allows the file to be moved or the stream position to be reset by another stream using the SafeFileHandle returned by this property.

Basically, SafeFileHandle guarantees you, that you can use the return value (e.g. with SetFilePointer) to access the file and have no issues with the (eventual) caching of the FileStream instance.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top