C# WinForm 解除资源文件的占用并删除

1.删除未解除占用的资源时

img
img

2.调用Windows API函数 解除文件占用

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseHandle(IntPtr hObject);

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

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool DeleteFile(string lpFileName);

        const uint GENERIC_WRITE = 0x40000000;
        const uint OPEN_EXISTING = 3;
        const uint FILE_SHARE_READ = 0x00000001;
        const uint FILE_SHARE_WRITE = 0x00000002;



        /// <summary>
        /// 解除文件并删除文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        private static void RelieveDeleteFile(string filePath)
        { 

            IntPtr fileHandle = CreateFile(filePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            if (fileHandle != IntPtr.Zero && fileHandle != new IntPtr(-1))
            {
                bool success = CloseHandle(fileHandle);
                if (success)
                {
                    success = DeleteFile(filePath);
                    if (success)
                    {
                        Console.WriteLine("文件已被释放并删除。");
                    }
                    else
                    {
                        Console.WriteLine("文件释放成功,但无法删除。");
                    }
                }
                else
                {
                    Console.WriteLine("无法释放文件。");
                }
            }
            else
            {
                Console.WriteLine("文件已经处于可删除状态。");
                DeleteFile(filePath);
            }
        }


调用

        // 调用示例
        string filePath = "C:\\test.txt";
        RelieveDeleteFile(filePath);

结果

img

posted @ 2024-05-14 15:49  我本梁人  阅读(400)  评论(0编辑  收藏  举报