Write() private méthode

private Write ( byte buffer, int offset, int count ) : void
buffer byte
offset int
count int
Résultat void
		public unsafe void Write(Stream value)
		{
			if (value.Length > _availableLength)
				throw new ArgumentException("Value is too long.");

			var buffer = new byte[4096];
			var lengthToWrite = value.Length;
			while (lengthToWrite > 0)
			{
				using (var stream = new UnmanagedMemoryStream(_currentPointer.Value.Ptr, _currentPointer.Value.AvailableLength, _currentPointer.Value.AvailableLength, FileAccess.ReadWrite))
				{
					do
					{
						var read = value.Read(buffer, 0, Math.Min(buffer.Length, _currentPointer.Value.AvailableLength));
						stream.Write(buffer, 0, read);

						lengthToWrite -= read;
						_currentPointer.Value.AvailableLength -= read;
					}
					while (_currentPointer.Value.AvailableLength > 0 && lengthToWrite > 0);
					
					_currentPointer = _currentPointer.Next;
				}
			}
		}
        unsafe public IHttpActionResult Unmanaged()
        {
            //使用 UnmanagedMemoryStream 类读取和写入非托管内存。 使用 Marshal 类分配和解除分配非托管内存块。
            // Create some data to read and write.
            byte[] message = UnicodeEncoding.Unicode.GetBytes("Hello Angkor");

            // Allocate a block of unmanaged memory and return an IntPtr object.	
            IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);

            // Get a byte pointer from the IntPtr object.
            byte* memBytePtr = (byte*)memIntPtr.ToPointer();

            // Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);

            // Write the data.
            writeStream.Write(message, 0, message.Length);
            // Close the stream.
            writeStream.Close();
            // Create another UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read);
            // Create a byte array to hold data from unmanaged memory.
            byte[] outMessage = new byte[message.Length];
            // Read from unmanaged memory to the byte array.
            readStream.Read(outMessage, 0, message.Length);
            // Close the stream.
            readStream.Close();
            // Display the data to the console.

            var msg = UnicodeEncoding.Unicode.GetString(outMessage);
            // Free the block of unmanaged memory.
            Marshal.FreeHGlobal(memIntPtr);
            return Json(msg);


        }
		public void Write_Count_Overflow ()
		{
			using (UnmanagedMemoryStream ums = new UnmanagedMemoryStream (mem_byteptr, length, capacity, FileAccess.ReadWrite)) {
				try {
					ums.Write (testStreamData, 1, Int32.MaxValue);
					Assert.Fail ("#1");
				}
				catch (ArgumentException ex) {
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
					Assert.IsNull (ex.ParamName, "#5");
				}
			}
		}
		public void Write_Offset_Negative ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			try {
				ums.Write (testStreamData, -1, testStreamData.Length);
				Assert.Fail ("#1");
			} catch (ArgumentOutOfRangeException ex) {
				// Non-negative number required
				Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("offset", ex.ParamName, "#6");
			}
			ums.Close();
		}
Exemple #5
0
            unsafe void SaveMessage(byte[] message)
            {
                // Allocate a block of unmanaged memory and return an IntPtr object.
                IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);

                // Get a byte pointer from the IntPtr object.
                byte* memBytePtr = (byte*)memIntPtr.ToPointer();

                // Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
                UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);

                // Write the data.
                writeStream.Write(message, 0, message.Length);

                // Close the stream.
                writeStream.Close();
            }
        private static unsafe void ThreadFunc()
        {
            try
            {
                int size = 65536;
                bool createdMain = false;
                var hFile = WinAPI.OpenFileMapping(
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    false,
                    "ulHelper_fm");
                if (hFile == IntPtr.Zero)
                {
                    hFile = WinAPI.CreateFileMapping(
                        new IntPtr(-1),
                        IntPtr.Zero,
                        WinAPI.FileMapProtection.PageReadWrite,
                        (uint)0, (uint)size,
                        "ulHelper_fm");
                    createdMain = true;
                }
                var lpBaseAddress = WinAPI.MapViewOfFile(
                    hFile,
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    0, 0, 0);

                Mutex = new Mutex(false, "ulHelper_mutex");
                Stream = new UnmanagedMemoryStream((byte*)lpBaseAddress.ToPointer(), size, size, FileAccess.ReadWrite);

                eventWH = new EventWaitHandle(false, EventResetMode.AutoReset, "ulHelper_event");

                int accCount;
                byte[] buf = new byte[size];

                if (createdMain)
                {
                    Mutex.WaitOne();
                    try
                    {
                        buf[0] = buf[1] = buf[2] = buf[3] = 0;
                        Stream.Position = 0;
                        Stream.Write(buf, 0, 4);
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                eventWH.Set();
                while (true)
                {
                    eventWH.WaitOne();
                    if (MainForm.NeedTerminate)
                        break;
                    Mutex.WaitOne();
                    try
                    {
                        Stream.Position = 0;
                        accCount = Stream.ReadByte();
                        lock (Accounts.List)
                            if (Accounts.List.Count != accCount)
                            {
                                foreach (var acc in Accounts.List)
                                    acc.Active = false;
                                for (int i = 0; i < accCount; i++)
                                {
                                    string accountName = "";
                                    int index = 0;
                                    Stream.Position = 8 + i * 128;
                                    Stream.Read(buf, 0, 128);
                                    while (buf[index] != 0)
                                        accountName += (char)buf[index++];
                                    if (!Accounts.List.Any(acc => acc.Name == accountName))
                                    {
                                        var accData = new AccountData(accountName);
                                        Accounts.List.Add(accData);
                                    }
                                    Accounts.List.First(acc => acc.Name == accountName).Active = true;
                                }
                                PerformNewAccount();
                            }
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                WinAPI.UnmapViewOfFile(lpBaseAddress);
                WinAPI.CloseHandle(hFile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                var f = new ExceptionForm(ex);
                f.ShowDialog();
            }
        }
        private void BuildCacheArray()
        {
            var workItem = GetReaderWorkItem();
            try
            {
                if (workItem.IsMemory)
                    throw new InvalidOperationException("When trying to build cache, reader worker is already in-memory reader.");

                var dataSize = _isReadOnly ? _physicalDataSize + ChunkFooter.MapSize : _chunkHeader.ChunkSize;
                _cachedLength = ChunkHeader.Size + dataSize + ChunkFooter.Size;
                var cachedData = Marshal.AllocHGlobal(_cachedLength);
                try
                {
                    using (var unmanagedStream = new UnmanagedMemoryStream((byte*)cachedData, _cachedLength, _cachedLength, FileAccess.ReadWrite))
                    {
                        workItem.Stream.Seek(0, SeekOrigin.Begin);
                        var buffer = new byte[65536];
                        // in ongoing chunk there is no need to read everything, it's enough to read just actual data written
                        int toRead = _isReadOnly ? _cachedLength : ChunkHeader.Size + _physicalDataSize; 
                        while (toRead > 0)
                        {
                            int read = workItem.Stream.Read(buffer, 0, Math.Min(toRead, buffer.Length));
                            if (read == 0)
                                break;
                            toRead -= read;
                            unmanagedStream.Write(buffer, 0, read);
                        }
                    }
                }
                catch
                {
                    Marshal.FreeHGlobal(cachedData);
                    throw;
                }
                _cachedData = cachedData;
            }
            finally
            {
                ReturnReaderWorkItem(workItem);
            }
        }
		internal UnmanagedMemoryStream ResourceValueAsStream (string name, int index)
		{
			ResourceInfo ri = infos [index];
			if ((PredefinedResourceType)ri.TypeIndex != PredefinedResourceType.Stream)
				throw new InvalidOperationException (String.Format ("Resource '{0}' was not a Stream. Use GetObject() instead.", name));
			
			lock (readerLock) {
				reader.BaseStream.Seek (ri.ValuePosition, SeekOrigin.Begin);
				
				// here we return a Stream from exactly
				// current position so that the returned
				// Stream represents a single object stream.
				long slen = reader.ReadInt32();
				UnmanagedMemoryStream basePtrStream = reader.BaseStream as UnmanagedMemoryStream;
				unsafe {
					if (basePtrStream != null) {
						return new UnmanagedMemoryStream (basePtrStream.PositionPointer, slen);
					} else {
						IntPtr ptr = Marshal.AllocHGlobal ((int) slen);
						byte* addr = (byte*) ptr.ToPointer ();
						UnmanagedMemoryStream ms = new UnmanagedMemoryStream (addr, slen, slen, FileAccess.ReadWrite);
						// The memory resource must be freed
						// when the stream is disposed.
						ms.Closed += delegate (object o, EventArgs e) {
							Marshal.FreeHGlobal (ptr);
						};

						byte [] bytes = new byte [slen < 1024 ? slen : 1024];
						while (slen > 0 ) {
							int x = reader.Read (bytes, 0, (int)Math.Min (bytes.Length, slen));

							if (x == 0)
								throw new FormatException ("The resource data is corrupt. Resource stream ended");

							ms.Write (bytes, 0, x);
							slen -= x;
						}
						ms.Seek (0, SeekOrigin.Begin);
						return ms;
					}
				}
			}
		}
		public void SetLength ()
		{
			UnmanagedMemoryStream ums = new UnmanagedMemoryStream(mem_byteptr,
				length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.SetLength (length - 1);
			Assert.AreEqual (capacity, ums.Capacity, "#A1");
			Assert.AreEqual (length - 1, ums.Length, "#A2");
			Assert.AreEqual (length - 1, ums.Position, "#A3");
			ums.SetLength (length + 1);
			Assert.AreEqual (capacity, ums.Capacity, "#B1");
			Assert.AreEqual (length + 1, ums.Length, "#B2");
			Assert.AreEqual (length - 1, ums.Position, "#B3");
			ums.SetLength (length);
			Assert.AreEqual (capacity, ums.Capacity, "#C1");
			Assert.AreEqual (length, ums.Length, "#C2");
			Assert.AreEqual (length - 1, ums.Position, "#C3");
			ums.SetLength (0);
			Assert.AreEqual (capacity, ums.Capacity, "#D1");
			Assert.AreEqual (0, ums.Length, "#D2");
			Assert.AreEqual (0, ums.Position, "#D3");
			ums.SetLength (capacity);
			Assert.AreEqual (capacity, ums.Capacity, "#E1");
			Assert.AreEqual (capacity, ums.Length, "#E2");
			Assert.AreEqual (0, ums.Position, "#E3");
			ums.Close();
		}
		public void Read_Offset_Overflow ()
		{
			using (UnmanagedMemoryStream ums = new UnmanagedMemoryStream (mem_byteptr, length, length, FileAccess.ReadWrite)) {
				ums.Write (testStreamData, 0, testStreamData.Length);
				ums.Position = 0;
				try {
					ums.Read (readData, Int32.MaxValue, 0);
					Assert.Fail ("#1");
				}
				catch (ArgumentException ex) {
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
					Assert.IsNull (ex.ParamName, "#5");
				}
			}
		}
		public void Read_EndOfStream ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length * 2, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#1");
			ums.Seek(length + 1, SeekOrigin.Begin);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#2");
			ums.Seek(length - 3, SeekOrigin.Begin);
			Assert.AreEqual (3, ums.Read (readData, 0, 5), "#3");
			ums.Seek(capacity + 1, SeekOrigin.Begin);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#4");
			ums.Close ();
		}
		public void Read_Count_Overlow ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			try {
				ums.Read (readData, 1, readData.Length);
				Assert.Fail ("#1");
			} catch (ArgumentException ex) {
				// Offset and length were out of bounds for the array or count
				// is greater than the number of elements from index to the end
				// of the source collection
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNull (ex.ParamName, "#5");
			}
		}
		public void Read_Count_Negative ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			try {
				ums.Read (readData, 0, -1);
				Assert.Fail ("#1");
			} catch (ArgumentOutOfRangeException ex) {
				// Non-negative number required
				Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("count", ex.ParamName, "#6");
			}
		}
		public void Read ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;

			Assert.AreEqual (length / 2, ums.Read (readData, 0, (length / 2)), "#1");
			VerifyTestData ("#2", readData, 0, (length / 2));
			Assert.AreEqual (length / 2, ums.Position, "#3");
			
			//Seek back to begining
			ums.Seek (0, SeekOrigin.Begin);
			
			//Read complete stream
			Assert.AreEqual (length, ums.Read (readData, 0, length), "#4");
			VerifyTestData ("#5", readData, 0, length);
			Assert.AreEqual (length, ums.Position, "#6");
			
			//Seek to mid of the stream and read till end
			ums.Seek ((length / 2), SeekOrigin.Begin);
			ums.Read (readData, 0, (length / 2));
			VerifyTestData ("#7", readData, (length / 2), (length / 2));
			Assert.AreEqual (length, ums.Position, "#8");
			ums.Close ();
		}
Exemple #15
0
        public void ATAreadDMA8Mem(UnmanagedMemoryStream pMem, int size)
        {
            if (((xferMode & 0xF0) == 0x40) &&
                (dev9.Dev9Ru16((int)DEV9Header.SPD_R_IF_CTRL) & DEV9Header.SPD_IF_DMA_ENABLE) != 0)
            {
                //size >>= 1;
                Log_Verb("DMA read, size " + size + ", transferred " + rdTransferred + ", total size " + nsector * 512);
                Log_Info("rATA");

                //read
                byte[] temp = new byte[size];
                hddImage.Read(temp, 0, size);
                pMem.Write(temp, 0, size);

                rdTransferred += size;
                if (rdTransferred >= nsector * 512)
                {
                    //Set Sector
                    long currSect = HDD_GetLBA();
                    currSect += nsector;
                    HDD_SetLBA(currSect);

                    nsector = 0;
                    status = DEV9Header.ATA_STAT_READY | DEV9Header.ATA_STAT_SEEK;
                    if (sendIRQ) dev9.DEV9irq(3, 1); //0x6c
                    rdTransferred = 0;
                    //dev9.Dev9Wu16((int)DEV9Header.SPD_R_IF_CTRL, (UInt16)(dev9.Dev9Ru16((int)DEV9Header.SPD_R_IF_CTRL) & ~DEV9Header.SPD_IF_DMA_ENABLE));
                }
            }
        }
		public void Write_Stream_Closed ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length);
			ums.Close();
			ums.Write(testStreamData, 0, length);
		}
		public void Write_Stream_ReadOnly ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length);
			try {
				ums.Write(testStreamData, 0, length);
				Assert.Fail ("#1");
			} catch (NotSupportedException ex) {
				// Stream does not support writing
				Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
			}
			ums.Close();
		}
		public void ReadByte ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			Assert.AreEqual (testStreamData [0], ums.ReadByte (), "#1");
			Assert.AreEqual (testStreamData [1], ums.ReadByte (), "#2");
			ums.Close();
		}
		public void ReadByte_EndOfStream ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			ums.Seek(length, SeekOrigin.Begin);
			Assert.AreEqual (-1, ums.ReadByte (), "#3");
			ums.Seek(length + 1, SeekOrigin.Begin);
			Assert.AreEqual (-1, ums.ReadByte (), "#4");
			ums.Seek(capacity, SeekOrigin.Begin);
			Assert.AreEqual (-1, ums.ReadByte (), "#5");
			ums.Seek(capacity + 1, SeekOrigin.Begin);
			Assert.AreEqual (-1, ums.ReadByte (), "#6");
			ums.Close();
		}
		public void Seek_Offset_Invalid ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			try {
				ums.Seek(-1, SeekOrigin.Begin);
				Assert.Fail ("#A1");
			} catch (IOException ex) {
				// An attempt was made to move the position before the beginning
				// of the stream
				Assert.AreEqual (typeof (IOException), ex.GetType (), "#A2");
				Assert.IsNull (ex.InnerException, "#A3");
				Assert.IsNotNull (ex.Message, "#A4");
			}

			ums.Position = 2;
			try {
				ums.Seek(-3, SeekOrigin.Current);
				Assert.Fail ("#B1");
			} catch (IOException ex) {
				// An attempt was made to move the position before the beginning
				// of the stream
				Assert.AreEqual (typeof (IOException), ex.GetType (), "#B2");
				Assert.IsNull (ex.InnerException, "#B3");
				Assert.IsNotNull (ex.Message, "#B4");
			}

			ums.Close();
		}
            public override int Read(ObjectId oid, out UnmanagedMemoryStream data, out ObjectType objectType)
            {
                data = null;
                objectType = default(ObjectType);

                MockGitObject gitObject;

                if (!m_objectIdToContent.TryGetValue(oid, out gitObject))
                {
                    return (int) ReturnCode.GIT_ENOTFOUND;
                }

                data = Allocate(gitObject.Length);

                foreach (var chunk in gitObject.Data)
                {
                    data.Write(chunk, 0, chunk.Length);
                }

                objectType = gitObject.ObjectType;

                return (int)ReturnCode.GIT_OK;
            }
		public void Write ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, length);
			Assert.AreEqual (capacity, ums.Capacity, "#A1");
			Assert.AreEqual (length, ums.Position, "#A2");
			Assert.AreEqual (length, ums.Length, "#A3");
			ums.Position = 0;
			ums.Read (readData, 0, length);
			Assert.AreEqual (capacity, ums.Capacity, "#B1");
			Assert.AreEqual (length, ums.Position, "#B2");
			Assert.AreEqual (length, ums.Length, "#B3");
			VerifyTestData ("#B4", readData, 0, length);
			ums.Write (testStreamData, 2, 2);
			Assert.AreEqual (capacity, ums.Capacity, "#C1");
			Assert.AreEqual (length + 2, ums.Position, "#C1");
			Assert.AreEqual (length + 2, ums.Length, "#C2");
			ums.Position = length;
			Assert.AreEqual (testStreamData [2], ums.ReadByte (), "#D1");
			Assert.AreEqual (testStreamData [3], ums.ReadByte (), "#D2");
			ums.Close();
		}
Exemple #23
0
 private void BuildCacheArray()
 {
     var workItem = GetReaderWorkItem();
     if (workItem.IsMemory)
         throw new InvalidOperationException("When trying to build cache, reader worker is already in-memory reader.");
     try
     {
         _cachedDataLength = _isReadonly ? _chunkFooter.ActualChunkSize + _chunkFooter.MapSize : _chunkHeader.ChunkSize;
         var cachedData = (byte*) Marshal.AllocHGlobal(_cachedDataLength);
         try
         {
             using (var unmanagedStream = new UnmanagedMemoryStream(cachedData,
                                                                    _cachedDataLength,
                                                                    _cachedDataLength,
                                                                    FileAccess.ReadWrite))
             {
                 workItem.Stream.Seek(GetRealPosition(0, inMemory: false), SeekOrigin.Begin);
                 var buffer = new byte[4096];
                 int toRead = _cachedDataLength;
                 while (toRead > 0)
                 {
                     int read = workItem.Stream.Read(buffer, 0, Math.Min(toRead, buffer.Length));
                     if (read == 0)
                         break;
                     toRead -= read;
                     unmanagedStream.Write(buffer, 0, read);
                 }
             }
         }
         catch
         {
             Marshal.FreeHGlobal((IntPtr) cachedData);
             throw;
         }
         _cachedData = cachedData;
     }
     finally
     {
         ReturnReaderWorkItem(workItem);
     }
 }
		public void Write_Capacity_Exceeded ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length + 2, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, length);
			ums.Write (testStreamData, 0, 2);
			try {
				ums.Write (testStreamData, 0, 1);
				Assert.Fail ("#1");
			} catch (NotSupportedException ex) {
				// Unable to expand length of this stream beyond its capacity
				Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
			}
			ums.Close();
		}
Exemple #25
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     _unmanagedStream.Write(buffer, offset, count);
 }
Exemple #26
0
        /// <summary>
        /// Writes a sequence of bytes
        /// </summary>
        /// <param name="Buffer"></param>
        /// <param name="BytesToWrite"></param>
        /// <param name="AtOffset"></param>
        public unsafe void Write(byte[] Buffer, int BytesToWrite, Int64 AtOffset)
        {
            IntPtr hMVF = IntPtr.Zero;
            try
            {
                Int64 FileMapStart = (AtOffset / _AllocationGranularity) * _AllocationGranularity;
                Int64 MapViewSize = (AtOffset % _AllocationGranularity) + _AllocationGranularity;
                Int64 iViewDelta = AtOffset - FileMapStart;

                hMVF = Win32API.MapViewOfFile(_hMMF, Win32API.FileMapAccess.FileMapWrite, FileMapStart, (Int32)MapViewSize);
                if (hMVF == IntPtr.Zero)
                    throw new Win32Exception();
                byte* p = (byte*)hMVF.ToPointer() + iViewDelta;
                UnmanagedMemoryStream ums = new UnmanagedMemoryStream(p, MapViewSize, MapViewSize, FileAccess.Write);
                ums.Write(Buffer, 0, BytesToWrite);
                Win32API.FlushViewOfFile(hMVF, (Int32)MapViewSize);
            }
            finally
            {
                if (hMVF != IntPtr.Zero)
                    Win32API.UnmapViewOfFile(hMVF);
            }
        }