Esempio n. 1
0
        private void openOrCreateMemoryAndWriteData <T>(T data)
        {
            mutex.WaitOne();
            try
            {
                mapFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, fileName);
            }
            catch
            {
                mapFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, 8 * 1024, fileName);
            }

            Stream writer = mapFile.MapView(MapAccess.FileMapAllAccess, 0, 8 * 1024);

            char[] charArrayOfObject = serializeToXml <T>(data).ToCharArray();


            for (int i = 0; i < charArrayOfObject.Length; i++)
            {
                writer.WriteByte((byte)charArrayOfObject[i]);
            }
            writer.Flush();
            writer.Close();
            mutex.ReleaseMutex();
        }
Esempio n. 2
0
        private void readDataFromMemory()
        {
            if (mapFile == null)
            {
                try
                {
                    mapFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, fileName);
                }
                catch
                {
                    mapFile = null;
                    throw new Exception("File " + fileName + " is not opened yet.");
                }
            }

            try
            {
                reader = mapFile.MapView(MapAccess.FileMapRead, 0, 8 * 1024);
            }
            catch (Exception)
            {
                Debug.WriteLine("Error in Reading");
            }
            getObjectFromMMF <TestData>();
        }
Esempio n. 3
0
        /// <summary>
        ///   Create a named map object 
        /// </summary>
        /// <param name="fileName">name of backing file, or null 
        ///            for a pagefile-backed map</param>
        /// <param name="protection">desired access to the mapping 
        ///            object</param>
        /// <param name="maxSize">maximum size of filemap object, or 0 
        ///            for size of file</param>
        /// <param name="name">name of file mapping object</param>
        /// <returns>The memory mapped file instance</returns>
        public static MemoryMappedFile Create( string fileName, MapProtection protection, 
            long maxSize, String name)
        {
            MemoryMappedFile map = new MemoryMappedFile();

             // open file first
             IntPtr hFile = INVALID_HANDLE_VALUE;

             if ( fileName != null )
             {
            // determine file access needed
            // we'll always need generic read access
            int desiredAccess = GENERIC_READ;
            if  ( (protection == MapProtection.PageReadWrite) ||
                  (protection == MapProtection.PageWriteCopy) )
            {
               desiredAccess |= GENERIC_WRITE;
            }

            // open or create the file
            // if it doesn't exist, it gets created
            hFile = Win32MapApis.CreateFile (
                        fileName, desiredAccess, 0,
                        IntPtr.Zero, OPEN_ALWAYS, 0, IntPtr.Zero
                     );
            if ( hFile == INVALID_HANDLE_VALUE )
               throw new FileMapIOException ( Marshal.GetHRForLastWin32Error() );

            // FIX: Is support neede for zero-length files!?!
             }

             map._hMap = Win32MapApis.CreateFileMapping (
                     hFile, IntPtr.Zero, (int)protection,
                     (int)((maxSize >> 32) & 0xFFFFFFFF),
                     (int)(maxSize & 0xFFFFFFFF), name
                  );

             // close file handle, we don't need it
             if ( hFile != INVALID_HANDLE_VALUE ) Win32MapApis.CloseHandle(hFile);
             if ( map._hMap == NULL_HANDLE )
            throw new FileMapIOException ( Marshal.GetHRForLastWin32Error() );

             return map;
        }
Esempio n. 4
0
        /// <summary>
        ///   Open an existing named File Mapping object
        /// </summary>
        /// <param name="access">desired access to the map</param>
        /// <param name="name">name of object</param>
        /// <returns>The memory mapped file instance</returns>
        public static MemoryMappedFile Open( MapAccess access, String name )
        {
            MemoryMappedFile map = new MemoryMappedFile();

             map._hMap = Win32MapApis.OpenFileMapping ( (int)access, false, name );
             if ( map._hMap == NULL_HANDLE )
            throw new FileMapIOException ( Marshal.GetHRForLastWin32Error() );

             return map;
        }
            Create(string fileName, MapProtection protection,
                              long maxSize, String name)
        {
            MemoryMappedFile map = new MemoryMappedFile();
            if (!map.Is64bit && maxSize > uint.MaxValue)
                throw new ConstraintException("32bit systems support max size of 4gb.");

            // open file first
            IntPtr hFile = INVALID_HANDLE_VALUE;

            if (!string.IsNullOrEmpty(fileName))
            {
                if (maxSize == 0)
                {
                    if (!File.Exists(fileName))
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" does not exist ==> Unable to map entire file", fileName));
                    }

                    FileInfo backingFileInfo = new FileInfo(fileName);
                    maxSize = backingFileInfo.Length;

                    if (maxSize == 0)
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" is zero bytes ==> Unable to map entire file", fileName));
                    }
                }

                // determine file access needed
                // we'll always need generic read access
                int desiredAccess = GENERIC_READ;
                if ((protection == MapProtection.PageReadWrite) ||
                      (protection == MapProtection.PageWriteCopy))
                {
                    desiredAccess |= GENERIC_WRITE;
                }

                // open or create the file
                // if it doesn't exist, it gets created
                hFile = Win32MapApis.CreateFile(
                            fileName, desiredAccess, 0,
                            IntPtr.Zero, OPEN_ALWAYS, 0, IntPtr.Zero
                          );
                if (hFile == INVALID_HANDLE_VALUE)
                    throw new FileMapIOException(Marshal.GetHRForLastWin32Error());

                //SafeFileHandle handle = new SafeFileHandle(hFile,true);
                //NTFS.Sparse.SparseFile.MarkSparse(handle);


                map._fileName = fileName;
            }

            map._hMap = Win32MapApis.CreateFileMapping(
                        hFile, IntPtr.Zero, (int)protection,
                        (int)((maxSize >> 32) & 0xFFFFFFFF),
                        (int)(maxSize & 0xFFFFFFFF), name
                    );

            // close file handle, we don't need it
            if (hFile != INVALID_HANDLE_VALUE) Win32MapApis.CloseHandle(hFile);
            if (map._hMap == NULL_HANDLE)
                throw new FileMapIOException(Marshal.GetHRForLastWin32Error());

            map._protection = protection;
            map._maxSize = maxSize;

            return map;
        }
Esempio n. 6
0
        Create(string fileName, MapProtection protection,
               long maxSize, String name)
        {
            MemoryMappedFile map = new MemoryMappedFile();

            if (!map.Is64bit && maxSize > uint.MaxValue)
            {
                throw new ConstraintException("32bit systems support max size of 4gb.");
            }

            // open file first
            IntPtr hFile = INVALID_HANDLE_VALUE;

            if (!string.IsNullOrEmpty(fileName))
            {
                if (maxSize == 0)
                {
                    if (!File.Exists(fileName))
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" does not exist ==> Unable to map entire file", fileName));
                    }

                    FileInfo backingFileInfo = new FileInfo(fileName);
                    maxSize = backingFileInfo.Length;

                    if (maxSize == 0)
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" is zero bytes ==> Unable to map entire file", fileName));
                    }
                }

                // determine file access needed
                // we'll always need generic read access
                int desiredAccess = GENERIC_READ;
                if ((protection == MapProtection.PageReadWrite) ||
                    (protection == MapProtection.PageWriteCopy))
                {
                    desiredAccess |= GENERIC_WRITE;
                }

                // open or create the file
                // if it doesn't exist, it gets created
                hFile = Win32MapApis.CreateFile(
                    fileName, desiredAccess, 0,
                    IntPtr.Zero, OPEN_ALWAYS, 0, IntPtr.Zero
                    );
                if (hFile == INVALID_HANDLE_VALUE)
                {
                    throw new FileMapIOException(Marshal.GetHRForLastWin32Error());
                }

                //SafeFileHandle handle = new SafeFileHandle(hFile,true);
                //NTFS.Sparse.SparseFile.MarkSparse(handle);

                map._fileName = fileName;
            }

            map._hMap = Win32MapApis.CreateFileMapping(
                hFile, IntPtr.Zero, (int)protection,
                (int)((maxSize >> 32) & 0xFFFFFFFF),
                (int)(maxSize & 0xFFFFFFFF), name
                );

            // close file handle, we don't need it
            if (hFile != INVALID_HANDLE_VALUE)
            {
                Win32MapApis.CloseHandle(hFile);
            }
            if (map._hMap == NULL_HANDLE)
            {
                throw new FileMapIOException(Marshal.GetHRForLastWin32Error());
            }

            map._protection = protection;
            map._maxSize    = maxSize;

            return(map);
        }
        /// <summary>
        /// Constructor used internally by MemoryMappedFile.
        /// </summary>
        /// <param name="backingFile">Preconstructed MemoryMappedFile</param>
        /// <param name="mapSize">Size of the view, in bytes.</param>
        /// <param name="isWriteable">True if Read/Write access is desired, False otherwise</param>
        internal MapViewStream(MemoryMappedFile backingFile, long mapSize, bool isWriteable)
        {
            if (backingFile == null)
            {
                throw new Exception("MapViewStream.MapViewStream - backingFile is null");
            }
            if (!backingFile.IsOpen)
            {
                throw new Exception("MapViewStream.MapViewStream - backingFile is not open");
            }
            if ((mapSize < 1) || (mapSize > backingFile.MaxSize))
            {
                throw new Exception(string.Format("MapViewStream.MapViewStream - mapSize is invalid.  mapSize == {0}, backingFile.MaxSize == {1}", mapSize, backingFile.MaxSize));
            }

            _backingFile = backingFile;
            _isWriteable = isWriteable;
            _access = isWriteable ? MapAccess.FileMapWrite : MapAccess.FileMapRead;
            // Need a backingFile.SupportsAccess function that takes a MapAccess compares it against its stored MapProtection protection and returns bool
            _mapSize = mapSize;

            _isOpen = true;

            // Map the first view

            Seek(0, SeekOrigin.Begin);
        }
Esempio n. 8
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:PeFileProcessor"/> class.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		/// ------------------------------------------------------------------------------------
		public PeFileProcessor(string fileName)
		{
			m_htDirectories = new Hashtable();
			m_fileName = fileName;
			m_mappedFile = MemoryMappedFile.Create(fileName, MapProtection.PageWriteCopy);
			ProcessFile();
		}
Esempio n. 9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or
		/// resetting unmanaged resources.
		/// </summary>
		/// <param name="fFromDispose">if set to <c>true</c> called from Dispose() - safe
		/// to do stuff with managed objects; if <c>false</c> called from Finalizer - managed
		/// objects might already be disposed.</param>
		/// ------------------------------------------------------------------------------------
		protected virtual void Dispose(bool fFromDispose)
		{
			if (fFromDispose)
			{
				if (m_reader != null)
					m_reader.Close();
				if (m_writer != null)
					m_writer.Close();
				if (m_stream != null)
					m_stream.Dispose();
				if (m_mappedFile != null)
					m_mappedFile.Dispose();
			}

			m_reader = null;
			m_writer = null;
			m_stream = null;
			m_mappedFile = null;
		}