public static IntPtr Open(String filename, FileMode mode, FileAccess access, FileShare share) { var fileHandle = WindowsNativeMethods.CreateFile(filename, access, share, IntPtr.Zero, mode, FileAttributes.Normal, IntPtr.Zero); if (fileHandle == INVALID_HANDLE_VALUE) { throw new Exception(String.Format("CreateFile '{0}' (mode={1}, access={2}, share={3}) failed (error={4})", filename, mode, access, share, WindowsNativeMethods.GetLastError())); } return(fileHandle); }
public void Flush() { if (bufferedLength > 0) { UInt32 written; if (false == WindowsNativeMethods.WriteFile(fileHandle, buffer, bufferedLength, out written, IntPtr.Zero)) { throw new IOException(String.Format("WriteFile({0} bytes) failed (error={1})", bufferedLength, WindowsNativeMethods.GetLastError())); } if (written != bufferedLength) { throw new IOException(String.Format("Only wrote {0} out of {1}", written, bufferedLength)); } //Console.WriteLine("Flushed {0} bytes:", bufferedLength); //Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer, 0, (int)bufferedLength)); bufferedLength = 0; } }
public unsafe void Write(byte *data, uint length) { if (length <= SmallEnoughToBuffer) { if (bufferedLength + length > buffer.Length) { Flush(); } // TODO: call a native function to perform the copy for (uint i = 0; i < length; i++) { buffer[bufferedLength + i] = data[i]; } bufferedLength += length; } else { Flush(); UInt32 written; if (false == WindowsNativeMethods.WriteFile(fileHandle, data, length, out written, IntPtr.Zero)) { throw new IOException(String.Format("WriteFile({0} bytes) failed (error={1})", length, WindowsNativeMethods.GetLastError())); } if (written != length) { throw new IOException(String.Format("Only wrote {0} out of {1}", written, length)); } } }