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

相关内容

热门资讯

黑科技脚本(德州智能)外挂透明... 黑科技脚本(德州智能)外挂透明挂辅助科技(黑科技ai)其实存在有挂(有挂方式)-哔哩哔哩1、构建自己...
黑科技好友房(wpk辅助透视)... 黑科技好友房(wpk辅助透视)外挂透明挂辅助器(ai代打)果然有挂(了解有挂)-哔哩哔哩wpk辅助透...
黑科技攻略(wpkplus)外... 黑科技攻略(wpkplus)外挂透明挂辅助助手(智能ai)果然存在有挂(有挂讲解)-哔哩哔哩一、wp...
黑科技黑科技(德州竞技联盟)外... 黑科技黑科技(德州竞技联盟)外挂透明挂辅助助手(智能ai)本来有挂(确实有挂)-哔哩哔哩1、德州竞技...
黑科技规律(WPK内置)外挂透... 黑科技规律(WPK内置)外挂透明挂辅助代打(软件透明挂)一直存在有挂(讲解有挂)-哔哩哔哩暗藏猫腻,...
黑科技规律(Wepoke插件挂... 黑科技规律(Wepoke插件挂)外挂透明挂辅助下载(ai代打)原来是真的有挂(有挂攻略)-哔哩哔哩1...
黑科技黑科技(德州游戏)外挂透... 黑科技黑科技(德州游戏)外挂透明挂辅助下载(透明黑科技)竟然真的有挂(有挂助手)-哔哩哔哩1、用户打...
黑科技软件(Wepoke大厅)... 黑科技软件(Wepoke大厅)外挂透明挂辅助助手(透明挂)一直真的有挂(有挂方式)-哔哩哔哩1、点击...
黑科技代打(WPK程序)外挂透... 黑科技代打(WPK程序)外挂透明挂辅助AI(透明挂)切实是真的有挂(有挂教程)-哔哩哔哩1、黑科技代...
黑科技好牌(WPK科技)外挂透... 黑科技好牌(WPK科技)外挂透明挂辅助插件(透视)一直存在有挂(有挂方法)-哔哩哔哩进入游戏-大厅左...