Share via


How to: Use a função ReadFile do Windows (guia de programação C#)

Este exemplo demonstra o Windows ReadFile função lendo e exibindo um arquivo de texto. O ReadFile função requer o uso de unsafe código porque ele requer um ponteiro como um parâmetro.

A matriz de bytes é passado para o Read função é um tipo gerenciado. Isso significa que o coletor de lixo de runtime (CLR) de idioma comum pode realocar a memória usada no array, será. Para evitar isso, fixa é usado para obter um apontador para a memória e marcá-la para que o coletor de lixo não movê-lo. No final do fixed bloco, a memória retorna automaticamente para ficar sujeito a percorrendo a coleta de lixo.

Esse recurso é conhecido como a fixação declarativa. Com a fixação, há muito pouca sobrecarga, a menos que uma coleta de lixo ocorre na fixed block, que é uma ocorrência improvável. No entanto, a fixação pode causar alguns efeitos colaterais indesejáveis durante as execuções de coleta de lixo global. A capacidade do coletor de lixo para compactar memória bastante é limitada por buffers fixados. Portanto, a fixação deve ser evitada se possível.

Exemplo

class FileReader
{
    const uint GENERIC_READ = 0x80000000;
    const uint OPEN_EXISTING = 3;
    System.IntPtr handle;

    [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
    static extern unsafe System.IntPtr CreateFile
    (
        string FileName,          // file name
        uint DesiredAccess,       // access mode
        uint ShareMode,           // share mode
        uint SecurityAttributes,  // Security Attributes
        uint CreationDisposition, // how to create
        uint FlagsAndAttributes,  // file attributes
        int hTemplateFile         // handle to template file
    );

    [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool ReadFile
    (
        System.IntPtr hFile,      // handle to file
        void* pBuffer,            // data buffer
        int NumberOfBytesToRead,  // number of bytes to read
        int* pNumberOfBytesRead,  // number of bytes read
        int Overlapped            // overlapped buffer
    );

    [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool CloseHandle
    (
        System.IntPtr hObject // handle to object
    );

    public bool Open(string FileName)
    {
        // open the existing file for reading       
        handle = CreateFile
        (
            FileName,
            GENERIC_READ,
            0,
            0,
            OPEN_EXISTING,
            0,
            0
        );

        if (handle != System.IntPtr.Zero)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public unsafe int Read(byte[] buffer, int index, int count)
    {
        int n = 0;
        fixed (byte* p = buffer)
        {
            if (!ReadFile(handle, p + index, count, &n, 0))
            {
                return 0;
            }
        }
        return n;
    }

    public bool Close()
    {
        return CloseHandle(handle);
    }
}

class Test
{
    static int Main(string[] args)
    {
        if (args.Length != 1)
        {
            System.Console.WriteLine("Usage : ReadFile <FileName>");
            return 1;
        }

        if (!System.IO.File.Exists(args[0]))
        {
            System.Console.WriteLine("File " + args[0] + " not found.");
            return 1;
        }

        byte[] buffer = new byte[128];
        FileReader fr = new FileReader();

        if (fr.Open(args[0]))
        {
            // Assume that an ASCII file is being read.
            System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();

            int bytesRead;
            do
            {
                bytesRead = fr.Read(buffer, 0, buffer.Length);
                string content = Encoding.GetString(buffer, 0, bytesRead);
                System.Console.Write("{0}", content);
            }
            while (bytesRead > 0);

            fr.Close();
            return 0;
        }
        else
        {
            System.Console.WriteLine("Failed to open requested file");
            return 1;
        }
    }
}

Consulte também

Referência

Unsafe Code and Pointers (C# Programming Guide)

Tipos de ponteiro (guia de programação C#)

Conceitos

C# Programming Guide

Coleta de Lixo

Outros recursos

C# Reference