MSDN Documentation

Reading Files in Windows

Windows provides a rich set of APIs for reading data from files. The most common approaches are:

  1. Win32 API – CreateFile, ReadFile, ReadFileEx
  2. C Run‑Time – fopen, fread, fgets
  3. .NET Framework – File.ReadAllText, StreamReader
  4. PowerShell – Get-Content

Win32 Example – Synchronous Read

#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hFile = CreateFileW(L"C:\\temp\\example.txt",
                               GENERIC_READ,
                               FILE_SHARE_READ,
                               NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        wprintf(L"Unable to open file (error %lu)\n", GetLastError());
        return 1;
    }

    char buffer[256];
    DWORD bytesRead;
    if (ReadFile(hFile, buffer, sizeof(buffer)-1, &bytesRead, NULL)) {
        buffer[bytesRead] = '\0';
        printf("File content: %s\n", buffer);
    } else {
        wprintf(L"Read failed (error %lu)\n", GetLastError());
    }
    CloseHandle(hFile);
    return 0;
}

.NET Example – Reading Text

using System;
using System.IO;

class Program {
    static void Main() {
        string path = @"C:\temp\example.txt";
        if (File.Exists(path)) {
            string content = File.ReadAllText(path);
            Console.WriteLine("File content:");
            Console.WriteLine(content);
        } else {
            Console.WriteLine("File not found.");
        }
    }
}

PowerShell – Get‑Content

# Read the whole file as a single string
$content = Get-Content -Path "C:\temp\example.txt" -Raw
Write-Output $content

# Read line by line
Get-Content -Path "C:\temp\example.txt" | ForEach-Object {
    Write-Host "Line: $_"
}

Best Practices

Related Topics