public partial class Program
{
static void FileMethod()
{
var fs
= File
.Open("data.txt", FileMode
.OpenOrCreate
);
var bytes
= new byte[fs
.Length
];
var count
= (int)fs
.Length
;
var offset
= 0;
while (count
> 0)
{
var n
= fs
.Read(bytes
, offset
, count
);
if (n
== 0)
break;
offset
+= n
;
count
-= n
;
}
}
}
public class FileOpen
{
public const uint GENERIC_READ
= 0x80000000;
public const uint GENERIC_WRITE
= 0x40000000;
public const uint CREATE_NEW
= 1;
public const uint CREATE_ALWAYS
= 2;
public const uint OPEN_EXISTING
= 3;
[DllImport("kernel32.dll", SetLastError
= true, CharSet
= CharSet
.Unicode
)]
static extern SafeFileHandle CreateFile(string lpFileName
, uint dwDesiredAccess
,
uint dwShareMode
, IntPtr lpSecurityAttributes
, uint dwCreationDisposition
,
uint dwFlagsAndAttributes
, IntPtr hTemplateFile
);
private SafeFileHandle _handleValue
;
public FileOpen(string path
)
{
Load(path
);
}
public void Load(string path
)
{
if (string.IsNullOrEmpty(path
))
{
throw new ArgumentNullException(nameof(path
));
}
_handleValue
= CreateFile(path
, GENERIC_WRITE
, 0, IntPtr
.Zero
, CREATE_ALWAYS
, 0, IntPtr
.Zero
);
if (_handleValue
.IsInvalid
)
{
Marshal
.ThrowExceptionForHR(Marshal
.GetHRForLastWin32Error());
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-19559.html