سلام بر تمامی برنامه نویسان سی شارپ 😉 در این مطلب آموزش استفاده از تابع محلی ویندوز برای خواندن فایل با استفاده از kernel32 در #C را آماده کردم. امیدوارم که این کد برای شما مفید باشد. در این کد یک فایل با پسوند cs خوانده می شود و محتویات آن به کاربر نمایش داده می شود.
خروجی کد به این صورت می باشد :
Contents
کد استفاده از تابع محلی ویندوز برای خواندن فایل با استفاده از kernel32 در #C :
// Code from
// A Programmer''// copyright 2000 Eric Gunnerson
using System;
using System.Runtime.InteropServices;
using System.Text;
class FileRead
{
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
IntPtr handle;
public FileRead(string filename)
{
// opens the existing file
handle = CreateFile( filename,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0);
}
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr CreateFile(
string filename,
uint desiredAccess,
uint shareMode,
uint attributes, // really SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(
IntPtr hFile,
void* lpBuffer,
int nBytesToRead,
int* nBytesRead,
int overlapped);
public unsafe int Read(byte[] buffer, int count)
{
int n = 0;
fixed (byte* p = buffer)
{
ReadFile(handle, p, count, &n, 0);
}
return n;
}
}
class Test
{
public static void Main(string[] args)
{
// A Programmer''// copyright 2000 Eric Gunnerson
using System;
using System.Runtime.InteropServices;
using System.Text;
class FileRead
{
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
IntPtr handle;
public FileRead(string filename)
{
// opens the existing file
handle = CreateFile( filename,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0);
}
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr CreateFile(
string filename,
uint desiredAccess,
uint shareMode,
uint attributes, // really SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(
IntPtr hFile,
void* lpBuffer,
int nBytesToRead,
int* nBytesRead,
int overlapped);
public unsafe int Read(byte[] buffer, int count)
{
int n = 0;
fixed (byte* p = buffer)
{
ReadFile(handle, p, count, &n, 0);
}
return n;
}
}
class Test
{
public static void Main(string[] args)
{