I pried this code out of ChatGPT, and it works!
First I asked for C# solution, no luck, then asked for C++, good luck, then asked it to do the same in C#, here is the untouched code.
Edit: the accepted answer also works, weird thought i tried that.
using System;
using System.IO;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CreateFile(
string lpFileName,
FileAccess dwDesiredAccess,
FileShare dwShareMode,
IntPtr lpSecurityAttributes,
FileMode dwCreationDisposition,
FileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadFile(
IntPtr hFile,
byte[] lpBuffer,
uint nNumberOfBytesToRead,
out uint lpNumberOfBytesRead,
IntPtr lpOverlapped
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
static void Main()
{
IntPtr fileHandle = CreateFile(
"path/to/file.txt",
FileAccess.Read,
FileShare.ReadWrite,
IntPtr.Zero,
FileMode.Open,
FileAttributes.Normal,
IntPtr.Zero
);
if (fileHandle != IntPtr.Zero && fileHandle != new IntPtr(-1))
{
try
{
FileInfo fileInfo = new FileInfo("path/to/file.txt");
byte[] buffer = new byte[fileInfo.Length];
if (ReadFile(fileHandle, buffer, (uint)fileInfo.Length, out uint bytesRead, IntPtr.Zero))
{
string content = System.Text.Encoding.Default.GetString(buffer, 0, (int)bytesRead);
Console.WriteLine(content);
}
}
finally
{
CloseHandle(fileHandle);
}
}
else
{
Console.WriteLine("Failed to open file");
}
}
}