ASP.NetSafeHandle-tasksandexamples
创始人
2024-09-19 10:01:05
0

ASP.Net中的SafeHandle类可用于管理外部资源,如文件句柄、内存句柄等。下面是一些使用SafeHandle的示例:

  1. 管理文件句柄
public class FileSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private readonly string _fileName;

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr CreateFile(
        string lpFileName,
        FileAccess dwDesiredAccess,
        FileShare dwShareMode,
        IntPtr lpSecurityAttributes,
        FileMode dwCreationDisposition,
        FileAttributes dwFlagsAndAttributes,
        IntPtr hTemplateFile);

    public FileSafeHandle(string fileName)
        : base(true)
    {
        _fileName = fileName;
        handle = CreateFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero,
            FileMode.Open, FileAttributes.RandomAccess, IntPtr.Zero);
        if (handle == IntPtr.Zero || handle == new IntPtr(-1))
        {
            int lastWin32Error = Marshal.GetLastWin32Error();
            throw new Win32Exception(lastWin32Error, "Failed to open file");
        }
    }

    protected override bool ReleaseHandle()
    {
        return NativeMethods.CloseHandle(handle);
    }

    public string FileName => _fileName;
}

在使用FileSafeHandle时,只需像使用一般的文件句柄一样使用即可,无需手动释放句柄。

  1. 管理内存句柄
public class MemorySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private readonly long _memorySize;

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize,
        AllocationType flAllocationType, MemoryProtection flProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize,
        FreeType dwFreeType);

    public MemorySafeHandle(long memorySize)
        : base(true)
    {
        _memorySize = memorySize;
        handle = VirtualAlloc(IntPtr.Zero, new UIntPtr((ulong)memorySize),
            Allocation

相关内容

热门资讯

实操分享!哈糖大菠萝有没有挂,... 实操分享!哈糖大菠萝有没有挂,wepoker透视脚本免费使用视频,确实存在有挂(有挂总结)1、用户打...
推荐一款!如何下载wpk透视版... 推荐一款!如何下载wpk透视版,德普之星辅助器,切实有挂(有挂解密)1、不需要AI权限,帮助你快速的...
必看攻略!wpk模拟器是什么,... 必看攻略!wpk模拟器是什么,wepoker免费透视,切实是真的有挂(有挂分析)1、每一步都需要思考...
教程辅助!wepoker辅助器... 教程辅助!wepoker辅助器安装包定制,aapoker怎么开辅助器,一直有挂(有挂秘籍)1.wep...
分享一款!拱趴大菠萝挂,hhp... 分享一款!拱趴大菠萝挂,hhpoker到底可以作弊吗,总是是真的有挂(有挂辅助)1、拱趴大菠萝挂免费...
2024教程!黑侠破解wepo... 2024教程!黑侠破解wepoker,购买wepoker模拟器,本来存在有挂(有挂秘笈)2024教程...
免费测试版!wepoker有辅... 免费测试版!wepoker有辅助插件吗,德普之星透视辅助软件是真的吗,真是是真的有挂(有挂神器)一、...
一分钟揭秘!wepoker私人... 一分钟揭秘!wepoker私人局辅助器怎么用,aapoker怎么设置抽水,真是是真的有挂(有挂存在)...
科技通报!wepoker透视是... 科技通报!wepoker透视是真的吗,竞技联盟辅助,一贯是真的有挂(有挂猫腻)1、进入到竞技联盟辅助...
揭秘一下!hhpoker底牌透... 揭秘一下!hhpoker底牌透视脚本,aapoker万能辅助器,本来是真的有挂(有挂秘籍)1、金币登...