C# CreateFile在打开fs驱动程序时失败

C# CreateFile在打开fs驱动程序时失败,c#,driver,createfile,C#,Driver,Createfile,我正在尝试与文件系统驱动程序通信。我可以用OpenSCManager、CreateService和OpenService启动驱动程序,但当我尝试使用“CreateFile”时,它总是显示错误代码2(我认为它是找不到文件等) 这是全部代码: using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.Management; u

我正在尝试与文件系统驱动程序通信。我可以用OpenSCManager、CreateService和OpenService启动驱动程序,但当我尝试使用“CreateFile”时,它总是显示错误代码2(我认为它是找不到文件等)

这是全部代码:

using System;
using System.Diagnostics;
using System.Collections;
using System.Runtime.InteropServices;
using System.Management;
using System.ServiceProcess;


namespace ConsoleApplication2
{
    public sealed class Win32Driver : IDisposable
    {


        string driverName;
        string execPath;
        IntPtr fileHandle;
        public Win32Driver(string driver, string driverExecPath)
        {
            this.driverName = driver;
            this.execPath = driverExecPath;
        }
        ~Win32Driver()
        {
            // BUG - should never rely on finalizer to clean-up unmanaged resources
            Dispose();
        }
        private void CloseStuff()
        {
            if (fileHandle != INVALID_HANDLE_VALUE)
            {
                fileHandle = INVALID_HANDLE_VALUE;
                CloseHandle(fileHandle);
            }
        }

        public void Dispose()
        {
            CloseStuff();
            GC.SuppressFinalize(this);
        }






        private readonly static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
        private const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
        private const int SC_MANAGER_CONNECT = 0x0001;
        private const int SC_MANAGER_CREATE_SERVICE = 0x0002;
        private const int SC_MANAGER_ENUMERATE_SERVICE = 0x0004;
        private const int SC_MANAGER_LOCK = 0x0008;
        private const int SC_MANAGER_QUERY_LOCK_STATUS = 0x0010;
        private const int SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020;
        private const int SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
        SC_MANAGER_CONNECT |
        SC_MANAGER_CREATE_SERVICE |
        SC_MANAGER_ENUMERATE_SERVICE |
        SC_MANAGER_LOCK |
        SC_MANAGER_QUERY_LOCK_STATUS |
        SC_MANAGER_MODIFY_BOOT_CONFIG;

        private const int SERVICE_QUERY_CONFIG = 0x0001;
        private const int SERVICE_CHANGE_CONFIG = 0x0002;
        private const int SERVICE_QUERY_STATUS = 0x0004;
        private const int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
        private const int SERVICE_START = 0x0010;
        private const int SERVICE_STOP = 0x0020;
        private const int SERVICE_PAUSE_CONTINUE = 0x0040;
        private const int SERVICE_INTERROGATE = 0x0080;
        private const int SERVICE_USER_DEFINED_CONTROL = 0x0100;

        private const int SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED
        |
        SERVICE_QUERY_CONFIG |
        SERVICE_CHANGE_CONFIG |
        SERVICE_QUERY_STATUS |
        SERVICE_ENUMERATE_DEPENDENTS |
        SERVICE_START |
        SERVICE_STOP |
        SERVICE_PAUSE_CONTINUE |
        SERVICE_INTERROGATE |
        SERVICE_USER_DEFINED_CONTROL;

        private const int SERVICE_DEMAND_START = 0x00000003;
        private const int SERVICE_KERNEL_DRIVER = 0x00000001;
        private const int SERVICE_ERROR_NORMAL = 0x00000001;

        private const uint GENERIC_READ = 0x80000000;
        private const uint FILE_SHARE_READ = 1;
        private const uint FILE_SHARE_WRITE = 2;
        private const uint OPEN_EXISTING = 3;
        private const uint IOCTL_SHOCKMGR_READ_ACCELEROMETER_DATA = 0x733fc;
        private const int FACILITY_WIN32 = unchecked((int)0x80070000);
        private IntPtr handle = INVALID_HANDLE_VALUE;

        [DllImport("advapi32", SetLastError = true)]
        internal static extern IntPtr OpenSCManager(string machineName, string
        databaseName, uint dwDesiredAccess);

        [DllImport("advapi32", SetLastError = true)]
        internal static extern IntPtr CreateService(IntPtr hSCManager, string
        serviceName, string displayName,
        uint dwDesiredAccess, uint serviceType, uint startType, uint
        errorControl,
        string lpBinaryPathName, string lpLoadOrderGroup, string lpdwTagId,
        string lpDependencies,
        string lpServiceStartName, string lpPassword);

        [DllImport("advapi32")]
        internal static extern bool CloseServiceHandle(IntPtr handle);

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);

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


        [DllImport("kernel32")]
        internal static extern void CloseHandle(IntPtr handle);

        [DllImport("kernel32", SetLastError = true)]
        private static extern bool DeviceIoControl(IntPtr hDevice, uint
        dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer,
        uint nOutBufferSize, ref uint lpBytesReturned, IntPtr lpOverlapped);


        internal bool LoadDeviceDriver()
        {
        IntPtr scHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);

        Console.WriteLine("OpenSCManager: " + scHandle);

        if (scHandle != INVALID_HANDLE_VALUE)
        {
        IntPtr hService = CreateService(scHandle, this.driverName,
                                        this.driverName, SERVICE_ALL_ACCESS
                                        , SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL
                                        ,execPath, null, null, null, null, null);

        Console.WriteLine("CreateService: " + hService);

        hService = OpenService(scHandle, this.driverName,
                       SERVICE_START | SERVICE_STOP);

        Console.WriteLine("OpenService: "+hService);


        if (hService != IntPtr.Zero)
        {
        CloseServiceHandle(hService); // close both handles
        CloseServiceHandle(scHandle);
        // Start the driver using System.Management (WMI)
        if (ExecuteSCMOperationOnDriver(this.driverName, "StartService") == 0)
        {
            return true;
        }
        }
        else
        if (Marshal.GetLastWin32Error()== 1073) // Driver/Service already in DB
        {
            Console.WriteLine("Marshal=1073");
        CloseServiceHandle(scHandle);
        // Start the driver using System.Management (WMI)
        if (ExecuteSCMOperationOnDriver(this.driverName, "StartService") == 0)
        {
            return true;
        }
        }
        Marshal.ThrowExceptionForHR(HRESULT_FROM_WIN32(Marshal.GetLastWin32Error()));
        }
        return false;
        }

        internal bool UnloadDeviceDriver()
        {
            int ret = 0;

            Console.WriteLine("Unloading now...");
            if (fileHandle != IntPtr.Zero && fileHandle != INVALID_HANDLE_VALUE)
            {
                CloseHandle(fileHandle);
            }
            if ((ret = ExecuteSCMOperationOnDriver(driverName, "StopService")) == 0)
            {
                ret = ExecuteSCMOperationOnDriver(driverName, "Delete");
            }
            if (ret != 0)
            {
                return false;
            }
            return true;
        }

        private static int ExecuteSCMOperationOnDriver(string driverName, string operation)
        {
            ManagementPath path = new ManagementPath();
            path.Server = ".";
            path.NamespacePath = @"root\CIMV2";
            path.RelativePath = @"Win32_BaseService.Name='" + driverName + "'";
            using (ManagementObject o = new ManagementObject(path))
            {
                ManagementBaseObject outParams = o.InvokeMethod(operation,null, null);
                return Convert.ToInt32(outParams.Properties["ReturnValue"].Value);
            }
        }

        internal IntPtr OpenDevice()
        {
            Console.WriteLine(driverName);


            fileHandle = CreateFile("\\\\.\\"+driverName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

            Console.WriteLine("CreateFile: "+fileHandle);
            //Console.WriteLine(Marshal.GetLastWin32Error());


        if(fileHandle == INVALID_HANDLE_VALUE)
        {
            Console.WriteLine("Throw exception");
            Console.WriteLine((Marshal.GetLastWin32Error()).ToString()+"\n\n\n");
            //Marshal.ThrowExceptionForHR(HRESULT_FROM_WIN32(Marshal.GetLastWin32Error()));
        }
        return fileHandle;
        }


        internal IntPtr DevControl()
        {
            Console.WriteLine("DevControl started");
            //long DeviceBuffer = 0;
            IntPtr dwState = new IntPtr(100);
            uint dwRet=0;

            bool dc = DeviceIoControl(fileHandle, FSConstants.IO_SET_EVENT, IntPtr.Zero, 0, dwState, (uint)Marshal.SizeOf(dwRet), ref dwRet, IntPtr.Zero);

            Console.WriteLine("Operation: "+dc);
            Console.WriteLine("Return Value: "+dwRet);
            Console.WriteLine("Error: "+(Marshal.GetLastWin32Error()).ToString() + "\n\n\n");
            if (fileHandle == INVALID_HANDLE_VALUE)
            {
                //Console.WriteLine("Throw exception");
                //Console.WriteLine((Marshal.GetLastWin32Error()).ToString()+"\n\n\n");
                //Marshal.ThrowExceptionForHR(HRESULT_FROM_WIN32(Marshal.GetLastWin32Error()));
            }
            return fileHandle;
        }



        private static int HRESULT_FROM_WIN32(int x)
        {
            return x <= 0 ? x : ((x & 0x0000FFFF) | FACILITY_WIN32);
        }
    }

    internal class FSConstants
    {
        private const int FILE_DEVICE_COMM_DRIVER = 0x00008810;
        const uint METHOD_NEITHER = 3;
        const uint METHOD_BUFFERED = 0;

        const uint FILE_ANY_ACCESS = 0;
        const uint FILE_SPECIAL_ACCESS = FILE_ANY_ACCESS;


        public static uint IO_SET_EVENT = CTL_CODE(FILE_DEVICE_COMM_DRIVER, 0x801, METHOD_NEITHER, FILE_ANY_ACCESS);


        static uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access)
        {
            return ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method);
        }
    }


}
输出为:

OpenSCManager: 1576104
CreateService: 1576624
OpenService: 1576704
FsFilter loaded
FsFilter
CreateFile: -1
Throw exception
2



-1
Device opened
DevControl started
Operation: False
Return Value: 0
Error: 6

Unloading now...
FsFilter unloaded
驱动器加载和卸载工作正常(使用DebugView进行检查)。问题是CreateFile总是显示“-1”/“2”。我已经和其他车手测试过了,但还是一样。当我用CreateFile打开一个文本文件时,它工作正常,但我想与我的驱动程序(DeviceIOControl)通信,所以我需要打开驱动程序设备

有人能帮我/给我一个提示吗?
谢谢

我想知道为什么驱动程序未能加载,却被“卸载”……而且,我只需要查询一下

Win32Driver driver = new Win32Driver(driverName,@"c:\\FsFilter.sys"); Win32Driver driver=新的Win32Driver(driverName,@“c:\\FsFilter.sys”); 为什么驱动程序的名称是硬编码的,不仅仅是因为您使用的是“verbatim”字符串,所以不需要转义反斜杠…您是否尝试过这种方式:

Win32Driver driver = new Win32Driver(driverName, Path.Combine(@"C:\", driverName)); Win32Driver-driver=新的Win32Driver(driverName,Path.Combine(@“C:\”,driverName)); 另一件事…当通过“CreateFile”进行调用时,您正在传入一个现有文件名“FsFilter.sys”进行读取,但它已经加载了。。。?应该是
\\。\FsFilter
删除了扩展名…这些是我注意到的事情,并且有一个关于…的问号

希望这有帮助, 顺致敬意, 汤姆。

是的, 这就成功了:

fileHandle=CreateFile(“\.\”+driverName,GENERIC\u READ,FILE\u SHARE\u READ,IntPtr.Zero,OPEN\u EXISTING,0,IntPtr.Zero)

谢谢汤姆:)


现在我得到了一个蓝屏,但这是一个司机的问题,我必须工作。驱动程序现在已正确打开:)

因此您正在从creatfile获取IVALID\u HANDLE\u值。在Windows7/vista或xp中也是如此。它是在Windows7中构建的,在WinXP中启动。驱动程序也针对WinXP环境进行了优化。当我根据您的建议更改Win32Driver初始化时,程序无法找到要加载的sys文件,因为它需要该文件的完整路径。我不认为有什么问题,因为司机已经可以装卸货物了。CreateFile调用系统驱动程序时不需要扩展名。只有我想的驱动程序名(但我也尝试用driverName+“.sys”等创建文件不起作用。)谢谢。@t0mm13b,出于某种奇怪的原因,我的驱动程序不会在Win2k8上运行,除非它的ImagePath设置为\SystemRoot\drivers\??.sys,因为错误7000(找不到文件)会弹出到日志中,除非驱动程序被放入该路径。为什么呢?它现在是否需要在相对路径中,或者对于ImagePath使用“c:\…\…\??.sys”是错误的?上面的代码丢失了参数1中的双斜杠。将一个\添加到两个斜杠。 Win32Driver driver = new Win32Driver(driverName, Path.Combine(@"C:\", driverName));