以下是代码片段: [DllImport("kernel32.dll")] public static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName); [DllImport("kernel32.dll")] public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); [DllImport("kernel32.dll")] public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] public static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll")] public static extern uint GetFileSize(IntPtr hFile, IntPtr lpFileSizeHigh); 上面是API的引用 private string returnback(string path) { string str = ""; IntPtr vFileHandle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, FileShare.Read | FileShare.Write, IntPtr.Zero, FileMode.Open, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero); if (INVALID_HANDLE_VALUE != (int)vFileHandle) { IntPtr vMappingHandle = CreateFileMapping( vFileHandle, IntPtr.Zero, PAGE_READWRITE, 0, 0, "~MappingTemp"); if (vMappingHandle != IntPtr.Zero) { IntPtr vHead = MapViewOfFile(vMappingHandle, FILE_MAP_COPY | FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, IntPtr.Zero); if (vHead != IntPtr.Zero) { uint vSize = GetFileSize(vFileHandle, IntPtr.Zero); byte[] temp = new byte[vSize]; for (int i = 0; i < vSize; i++) { byte vTemp = Marshal.ReadByte((IntPtr)((int)vHead + i)); temp[i] = vTemp; } ASCIIEncoding encoding = new ASCIIEncoding(); str = encoding.GetString(temp).Replace("\r\n", ","); UnmapViewOfFile(vHead); } CloseHandle(vMappingHandle); CloseHandle(vHead); } CloseHandle(vFileHandle); } return str; } 上面具体的读取方法。 |