Overview
Reading files is a fundamental operation in any Windows application. The operating system provides several high‑level and low‑level APIs to access the file system securely and efficiently. This article covers the most common approaches for reading text and binary data using C++, C#, and PowerShell.
C++ (Win32) – ReadFile
For low‑level, unbuffered reads you can use the ReadFile function from the Win32 API.
#include <windows.h>
#include <iostream>
#include <vector>
int main()
{
HANDLE hFile = CreateFileW(
L"C:\\temp\\sample.txt",
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
std::wcerr << L"Failed to open file, error: " << GetLastError() << std::endl;
return 1;
}
const DWORD bufferSize = 4096;
std::vector<BYTE> buffer(bufferSize);
DWORD bytesRead = 0;
while (ReadFile(hFile, buffer.data(), bufferSize, &bytesRead, nullptr) && bytesRead) {
std::cout.write(reinterpret_cast<char*>(buffer.data()), bytesRead);
}
CloseHandle(hFile);
return 0;
}
C# – StreamReader
The .NET Framework offers StreamReader for convenient text file reads.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\temp\sample.txt";
if (!File.Exists(path))
{
Console.WriteLine("File not found.");
return;
}
using (var reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
PowerShell – Get-Content
PowerShell provides a one‑liner for reading files.
# Read entire file as a single string
$content = Get-Content -Path "C:\temp\sample.txt" -Raw
Write-Output $content
# Or process line‑by‑line
Get-Content -Path "C:\temp\sample.txt" | ForEach-Object {
Write-Host $_
}
Best Practices
- Always validate file paths and handle Unicode correctly.
- Prefer using buffered streams (
FileStream,StreamReader) for large files. - Dispose of handles and streams with
using(C#) orCloseHandle(C++). - Take advantage of async I/O in .NET (
ReadAsync) for UI‑responsive apps. - When possible, use the newer
Windows.StorageAPIs for UWP apps.