Unlock() public method

public Unlock ( long position, long length ) : void
position long
length long
return void
 static public int Unlock(IntPtr l)
 {
     try {
         System.IO.FileStream self = (System.IO.FileStream)checkSelf(l);
         System.Int64         a1;
         checkType(l, 2, out a1);
         System.Int64 a2;
         checkType(l, 3, out a2);
         self.Unlock(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #2
0
        /// <summary>
        /// Process a file pack.
        /// </summary>
        /// <param name="FileName">The name of the file.</param>
        /// <param name="FileID">The ID of the file.</param>
        /// <param name="StartPoint">The star point of the file pack.</param>
        /// <param name="PackID">The ID of the binary data.</param>
        /// <param name="Binary">The binary data.</param>
        /// <param name="SenderPeer">The sender peer object.</param>
        public static void ProcessFilePack(string FileName, string FileID, int StartPoint, string PackID, byte[] Binary, Objects.Peer SenderPeer)
        {
            Objects.Download download = Downloader.SearchDownload(FileName, FileID);

            // control if exist this download and if it is actived
            if (download != null && download.Active == true)
            {
                // control that the binaryPack isn't damaged

                SHA1 sha1 = new SHA1CryptoServiceProvider();

                if (PackID == BitConverter.ToString(sha1.ComputeHash(Binary)).Replace("-", ""))
                {
                    #region Write to the file

                    while (true)
                    {
                        try
                        {
                            // open ( or create ) the file ( in temp-directory )
                            FileStream fs = new FileStream((Global.TempDirectory + @"\" + FileName), FileMode.OpenOrCreate);

                            // lock the access to file
                            fs.Lock(StartPoint, 16384);

                            // set the start-point
                            fs.Seek(StartPoint, SeekOrigin.Begin);

                            int count = 16384;

                            if((download.Size - StartPoint) < 16384)
                            {
                                count = ((int)download.Size - StartPoint);
                            }

                            // write the filePack in the file ( temp )
                            fs.Write(Binary, 0, count);

                            // unlock the access to file
                            fs.Unlock(StartPoint, 16384);

                            fs.Close();

                            // log the file pack
                            Downloader.LogFilePack(download, StartPoint, SenderPeer, Downloader.Status_FilePack.Written);

                            break;
                        }

                        catch (IOException) // the file is already locked
                        {
                            Thread.Sleep(1);
                        }

                        catch (Exception ex) // other problem
                        {
                            Utilities.Log.Write("Downloader.cs: error to write in a file: \n" + ex.Message, Utilities.Log.LogCategory.Error);
                            break;
                        }
                    }

                    #endregion
                }
                else
                {
                    // log
                    // communicate to Downloader that the FilePack is damaged
                    Downloader.LogFilePack(download, StartPoint, SenderPeer, Downloader.Status_FilePack.Damaged);
                }
            }
        }
		public void Unlock_Disposed () 
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "temp";
			DeleteFile (path);
			FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
			stream.Close ();
			stream.Unlock (0,1);
		}
Beispiel #4
0
        // DonwFile-返回包处理
        private void udpProDownFileBack(UnUdpEntity etBack)
        {
            // 刷新超时时间戳
            timeOutTicks = UnDate.ticksMSec();
            switch (etBack.Event.getUnUdpEveEnum())
            {
                case UnUdpEveEnum.downFileQueryBack:
                    sleepTime = Convert.ToInt32(UnDate.ticksMSec() - traTicks) + 1;
                    if (sleepTime > 10000)
                    {
                        sleepTime = 2000;
                    }
                    // 初始化
                    FileInfo cofFi = new FileInfo(UnUdpHelp.getDownFileTmpConfigPath(etBack.HashCode));
                    FileInfo tmpFi = new FileInfo(UnUdpHelp.getDownFileReceivePath(etBack.HashCode));
                    if (!cofFi.Exists)
                    {
                        DirectoryInfo di = new DirectoryInfo(UnUdpHelp.getDownFileTmpDirectory(etBack.HashCode));
                        if (!di.Exists)
                        {
                            di.Create();
                        }
                        cofFi.Create().Dispose();
                        tmpFi.Create().Dispose();
                        downQuery = etBack;
                    }

                    // 第一次初始化
                    if (downQuery.TotalPacks == 0)
                    {
                        // 获得配置文件
                        using (FileStream fs = cofFi.OpenRead())
                        {
                            byte[] b = new byte[fs.Length];
                            fs.Read(b, 0, b.Length);
                            downQuery = UnUdpHelp.analyzePackage(b);
                        }
                    }
                    else
                    {
                        downQuery.IntMin = etBack.IntMin;
                        downQuery.IntMax = etBack.IntMax;
                    }

                    // 写入配置文件
                    using (FileStream fs = new FileStream(UnUdpHelp.getDownFileTmpConfigPath(etBack.HashCode), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        byte[] prgBackBts = UnUdpHelp.assemblePackage(downQuery);
                        fs.SetLength(0);
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.Write(prgBackBts, 0, prgBackBts.Length);
                    }

                    // 建立窗口
                    downIntervals = new List<UnUdpEntity>();
                    for (long i = downQuery.IntMin; i <= downQuery.IntMax; i++)
                    {
                        UnUdpEntity uup = new UnUdpEntity();
                        uup.PackNo = i;
                        upp.isSend = false;
                        downIntervals.Add(uup);
                    }
                    isdbPer = true;
                    break;
                case UnUdpEveEnum.downFileBack:
                    UnUdpEntity up = downIntervals.Find(t => t.PackNo == etBack.PackNo && t.isSend == false);
                    string tmpPath = UnUdpHelp.getDownFileReceivePath(downQuery.HashCode);
                    if (up != null)
                    {
                        // 写入数据
                        using (FileStream fs = new FileStream(tmpPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            fs.Lock(etBack.PackOffset, etBack.PackData.Length);
                            fs.Seek(etBack.PackOffset, SeekOrigin.Begin);
                            fs.Write(etBack.PackData, 0, etBack.PackData.Length);
                            fs.Unlock(etBack.PackOffset, etBack.PackData.Length);
                            downQuery.UpCount++;
                            up.isSend = true;
                        }
                        udpAddDownProgress(downQuery);
                    }
                    // 下载完成
                    if (downQuery.UpCount == downQuery.TotalPacks)
                    {
                        _isFinish = true;
                        // 转正式文件
                        string newPath = UnUdpHelp.getDownFileSavePath(downQuery.HashCode, downQuery.Extent);
                        UnFile.move(tmpPath, newPath, true);
                        // 删除临时文件夹
                        File.Delete(UnUdpHelp.getDownFileTmpConfigPath(downQuery.HashCode));
                        Directory.Delete(UnUdpHelp.getDownFileTmpDirectory(downQuery.HashCode));
                        if (intTransfer != null)
                        {
                            UnAttrRst rst = new UnAttrRst();
                            rst.pid = _pid;
                            rst.code = 1;
                            rst.msg = "下载完成";
                            rst.back = newPath;
                            intTransfer.success(rst);
                        }
                    }
                    break;
            }
        }
Beispiel #5
0
		// ---------------------------------------------------------------------------

		// No explicit destructors in C#

		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{
   
			APE_HEADER APE = new APE_HEADER();				// common header
			APE_HEADER_OLD APE_OLD = new APE_HEADER_OLD();	// old header   <= 3.97
			APE_HEADER_NEW APE_NEW = new APE_HEADER_NEW();	// new header   >= 3.98
			APE_DESCRIPTOR APE_DESC = new APE_DESCRIPTOR(); // extra header >= 3.98

			FileStream fs = null;
			BinaryReader SourceFile = null;

			int BlocksPerFrame;
			bool LoadSuccess;
			int TagSize;
			bool result = false;
   
			FResetData();
   
			// load tags first
			FID3v2.ReadFromFile(FileName);
			FID3v1.ReadFromFile(FileName);
			FAPEtag.ReadFromFile(FileName);
   
			// calculate total tag size
			TagSize = 0;
			if (FID3v1.Exists) TagSize += 128;
			if (FID3v2.Exists) TagSize += FID3v2.Size;
			if (FAPEtag.Exists) TagSize += FAPEtag.Size;
   
			// reading data from file
			LoadSuccess = false;

			try
			{
				try
				{         
					fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
					fs.Lock(0,fs.Length);
					SourceFile = new BinaryReader(fs);
					FFileSize = fs.Length;

					// seek past id3v2-tag
					if (FID3v2.Exists)
					{
						fs.Seek(FID3v2.Size, SeekOrigin.Begin);
					}
					// Read APE Format Header         
					Array.Clear(APE.cID,0,APE.cID.Length);
					APE.nVersion = 0;
	  
					APE.cID = SourceFile.ReadChars(4);
					APE.nVersion = SourceFile.ReadUInt16();

					if ( Utils.StringEqualsArr("MAC ",APE.cID) )
					{            
						FVersion = APE.nVersion;

						FVersionStr = ((double)FVersion / 1000).ToString().Substring(0,4); //Str(FVersion / 1000 : 4 : 2, FVersionStr);
            
						// Load New Monkey's Audio Header for version >= 3.98
						if (APE.nVersion >= 3980) 
						{
							APE_DESC.padded = 0;
							APE_DESC.nDescriptorBytes = 0;
							APE_DESC.nHeaderBytes = 0;
							APE_DESC.nSeekTableBytes = 0;
							APE_DESC.nHeaderDataBytes = 0;
							APE_DESC.nAPEFrameDataBytes = 0;
							APE_DESC.nAPEFrameDataBytesHigh = 0;
							APE_DESC.nTerminatingDataBytes = 0;
							Array.Clear(APE_DESC.cFileMD5,0,APE_DESC.cFileMD5.Length);

							APE_DESC.padded = SourceFile.ReadUInt16();
							APE_DESC.nDescriptorBytes = SourceFile.ReadUInt32();
							APE_DESC.nHeaderBytes = SourceFile.ReadUInt32();
							APE_DESC.nSeekTableBytes = SourceFile.ReadUInt32();
							APE_DESC.nHeaderDataBytes = SourceFile.ReadUInt32();
							APE_DESC.nAPEFrameDataBytes = SourceFile.ReadUInt32();
							APE_DESC.nAPEFrameDataBytesHigh = SourceFile.ReadUInt32();
							APE_DESC.nTerminatingDataBytes = SourceFile.ReadUInt32();
							APE_DESC.cFileMD5 = SourceFile.ReadBytes(16);

							// seek past description header
							if (APE_DESC.nDescriptorBytes != 52) fs.Seek(APE_DESC.nDescriptorBytes - 52, SeekOrigin.Current);
							// load new ape_header
							if (APE_DESC.nHeaderBytes > 24/*sizeof(APE_NEW)*/) APE_DESC.nHeaderBytes = 24/*sizeof(APE_NEW)*/;
                  				
							APE_NEW.nCompressionLevel = 0;
							APE_NEW.nFormatFlags = 0;
							APE_NEW.nBlocksPerFrame = 0;
							APE_NEW.nFinalFrameBlocks = 0;
							APE_NEW.nTotalFrames = 0;
							APE_NEW.nBitsPerSample = 0;
							APE_NEW.nChannels = 0;
							APE_NEW.nSampleRate = 0;

							APE_NEW.nCompressionLevel = SourceFile.ReadUInt16();
							APE_NEW.nFormatFlags = SourceFile.ReadUInt16();
							APE_NEW.nBlocksPerFrame = SourceFile.ReadUInt32();
							APE_NEW.nFinalFrameBlocks = SourceFile.ReadUInt32();
							APE_NEW.nTotalFrames = SourceFile.ReadUInt32();
							APE_NEW.nBitsPerSample = SourceFile.ReadUInt16();
							APE_NEW.nChannels = SourceFile.ReadUInt16();
							APE_NEW.nSampleRate = SourceFile.ReadUInt32();
				
							// based on MAC SDK 3.98a1 (APEinfo.h)
							FSampleRate       = (int)APE_NEW.nSampleRate;
							FChannels         = APE_NEW.nChannels;
							FFormatFlags      = APE_NEW.nFormatFlags;
							FBits             = APE_NEW.nBitsPerSample;
							FCompressionMode  = APE_NEW.nCompressionLevel;
							// calculate total uncompressed samples
							if (APE_NEW.nTotalFrames > 0)
							{
								FTotalSamples     = (long)(APE_NEW.nBlocksPerFrame) *
									(long)(APE_NEW.nTotalFrames-1) +
									(long)(APE_NEW.nFinalFrameBlocks);
							}
							LoadSuccess = true;
						}
						else 
						{
							// Old Monkey <= 3.97               

							APE_OLD.nCompressionLevel = 0;
							APE_OLD.nFormatFlags = 0;
							APE_OLD.nChannels = 0;
							APE_OLD.nSampleRate = 0;
							APE_OLD.nHeaderBytes = 0;
							APE_OLD.nTerminatingBytes = 0;
							APE_OLD.nTotalFrames = 0;
							APE_OLD.nFinalFrameBlocks = 0;
							APE_OLD.nInt = 0;

							APE_OLD.nCompressionLevel = SourceFile.ReadUInt16();
							APE_OLD.nFormatFlags = SourceFile.ReadUInt16();
							APE_OLD.nChannels = SourceFile.ReadUInt16();
							APE_OLD.nSampleRate = SourceFile.ReadUInt32();
							APE_OLD.nHeaderBytes = SourceFile.ReadUInt32();
							APE_OLD.nTerminatingBytes = SourceFile.ReadUInt32();
							APE_OLD.nTotalFrames = SourceFile.ReadUInt32();
							APE_OLD.nFinalFrameBlocks = SourceFile.ReadUInt32();
							APE_OLD.nInt = SourceFile.ReadInt32();				

							FCompressionMode  = APE_OLD.nCompressionLevel;
							FSampleRate       = (int)APE_OLD.nSampleRate;
							FChannels         = APE_OLD.nChannels;
							FFormatFlags      = APE_OLD.nFormatFlags;
							FBits = 16;
							if ( (APE_OLD.nFormatFlags & MONKEY_FLAG_8_BIT ) != 0) FBits =  8;
							if ( (APE_OLD.nFormatFlags & MONKEY_FLAG_24_BIT) != 0) FBits = 24;

							FHasSeekElements  = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_PEAK_LEVEL   )  != 0);
							FWavNotStored     = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_SEEK_ELEMENTS) != 0);
							FHasPeakLevel     = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_WAV_NOT_STORED) != 0);
                  
							if (FHasPeakLevel)
							{
								FPeakLevel        = (uint)APE_OLD.nInt;
								FPeakLevelRatio   = (FPeakLevel / (1 << FBits) / 2.0) * 100.0;
							}

							// based on MAC_SDK_397 (APEinfo.cpp)
							if (FVersion >= 3950) 
								BlocksPerFrame = 73728 * 4;
							else if ( (FVersion >= 3900) || ((FVersion >= 3800) && (MONKEY_COMPRESSION_EXTRA_HIGH == APE_OLD.nCompressionLevel)) )
								BlocksPerFrame = 73728;
							else
								BlocksPerFrame = 9216;

							// calculate total uncompressed samples
							if (APE_OLD.nTotalFrames>0)
							{
								FTotalSamples =  (long)(APE_OLD.nTotalFrames-1) *
									(long)(BlocksPerFrame) +
									(long)(APE_OLD.nFinalFrameBlocks);
							}
							LoadSuccess = true;
               
						}
						if (LoadSuccess) 
						{
							// compression profile name
							if ( (0 == (FCompressionMode % 1000)) && (FCompressionMode<=6000) )
							{
								FCompressionModeStr = MONKEY_COMPRESSION[FCompressionMode / 1000]; // int division
							}
							else 
							{
								FCompressionModeStr = FCompressionMode.ToString();
							}
							// length
							if (FSampleRate>0) FDuration = ((double)FTotalSamples / FSampleRate);
							// average bitrate
							if (FDuration>0) FBitrate = 8*(FFileSize - (long)(TagSize)) / (FDuration*1000);
							// some extra sanity checks
							FValid   = ((FBits>0) && (FSampleRate>0) && (FTotalSamples>0) && (FChannels>0));
							result   = FValid;
						}
					}
				}
				finally
				{
					if (fs != null)
					{
						fs.Unlock(0,fs.Length);
						if (SourceFile != null) SourceFile.Close();
					}
				}
			}
			catch (Exception e)
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			return result;
		}
Beispiel #6
0
		/* -------------------------------------------------------------------------- */

		// No explicit destructors with C#

		/* -------------------------------------------------------------------------- */

		public bool ReadFromFile(String FileName)
		{  
			FileStream fs = null;
			BinaryReader source = null;

			char[] signatureChunk = new char[4];
			tta_header ttaheader = new tta_header();
			long TagSize;

			bool result = false;
  
  
			FResetData();
  
			// load tags first
			FID3v2.ReadFromFile(FileName);
			FID3v1.ReadFromFile(FileName);
			FAPEtag.ReadFromFile(FileName);
  
			// calulate total tag size
			TagSize = 0;
			if (FID3v1.Exists)  TagSize += 128;
			if (FID3v2.Exists)  TagSize += FID3v2.Size;
			if (FAPEtag.Exists)  TagSize += FAPEtag.Size;
  
			// begin reading data from file  
			try
			{
				fs = new FileStream(FileName,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);

    	
				// seek past id3v2-tag
				if ( FID3v2.Exists )
				{
					fs.Seek(FID3v2.Size, SeekOrigin.Begin);
				}

				signatureChunk = source.ReadChars(4);
				if ( Utils.StringEqualsArr("TTA1",signatureChunk) ) 
				{    	
					// start looking for chunks
					ttaheader.Reset();
      		
					ttaheader.AudioFormat = source.ReadUInt16();
					ttaheader.NumChannels = source.ReadUInt16();
					ttaheader.BitsPerSample = source.ReadUInt16();
					ttaheader.SampleRate = source.ReadUInt32();
					ttaheader.DataLength = source.ReadUInt32();
					ttaheader.CRC32 = source.ReadUInt32();

					FFileSize = fs.Length;
					FValid = true;

					FAudioFormat = ttaheader.AudioFormat;
					FChannels = ttaheader.NumChannels;
					FBits = ttaheader.BitsPerSample;
					FSampleRate = ttaheader.SampleRate;
					FSamples = ttaheader.DataLength;
					FCRC32 = ttaheader.CRC32;

					FBitrate = (double)FFileSize * 8 / (FSamples / FSampleRate) / 1000;
					FDuration = (double)ttaheader.DataLength / ttaheader.SampleRate;

					result = true;
				}
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
  
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				if (source != null) source.Close();
			}

  
			return result;
		}
Beispiel #7
0
		// ---------------------------------------------------------------------------

		private bool ReadData(String FileName, ref FileData Data)
		{ 
			FileStream fs = null;
			BinaryReader Source = null;
			char[] ID = new char[16];
			int ObjectCount;
			int ObjectSize;
			long Position;

			bool result;

			// Read file data
			try
			{
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				Data.FileSize = (int)fs.Length;
    
				// Check for existing header
				ID = Utils.ReadTrueChars(Source,16);

				if ( Utils.ArrEqualsArr(WMA_HEADER_ID,ID) )
				{
					fs.Seek(8, SeekOrigin.Current);
					ObjectCount = Source.ReadInt32();		  
					fs.Seek(2, SeekOrigin.Current);
					// Read all objects in header and get needed data
					for (int iterator=0; iterator<ObjectCount; iterator++)
					{
						Position = fs.Position;
						ID = Utils.ReadTrueChars(Source,16);
						ObjectSize = Source.ReadInt32();			
						ReadObject(ID, Source, ref Data);
						fs.Seek(Position + ObjectSize, SeekOrigin.Begin);				
					}
				}
				result = true;
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
				result = false;
			}
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}
			return result;
		}
Beispiel #8
0
		/* -------------------------------------------------------------------------- */

		public bool GetInfo( String sFile, bool bSetTags)
		{
			FileStream fs = null;
			BinaryReader r = null;

			byte[] aMetaDataBlockHeader = new byte[4];
			int iBlockLength;
			int iMetaType;
			int iIndex;
			bool bPaddingFound;

			bool result = true;
  
			bPaddingFound = false;
			FResetData( true, false );
  
			try
			{
				// Read data from ID3 tags
				FID3v2.ReadFromFile(sFile);

				// Set read-access and open file
				fs = new FileStream(sFile,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				r = new BinaryReader(fs);

				FFileLength = (int)fs.Length;
				FFileName = sFile;

				// Seek past the ID3v2 tag, if there is one
				if (FID3v2.Exists)  
				{
					fs.Seek(FID3v2.Size, SeekOrigin.Begin);
				}

				// Read header data    
				FHeader.Reset();
    
				FHeader.StreamMarker = r.ReadChars(4);
				FHeader.MetaDataBlockHeader = r.ReadBytes(4);
				FHeader.Info = r.ReadBytes(18);
				FHeader.MD5Sum = r.ReadBytes(16);

				// Process data if loaded and header valid    
				if ( Utils.StringEqualsArr("fLaC",FHeader.StreamMarker) )
				{
					FChannels      = (byte)( ((FHeader.Info[12] >> 1) & 0x7) + 1 );
					FSampleRate    = ( FHeader.Info[10] << 12 | FHeader.Info[11] << 4 | FHeader.Info[12] >> 4 );
					FBitsPerSample = (byte)( ((FHeader.Info[12] & 1) << 4) | (FHeader.Info[13] >> 4) + 1 );
					FSamples       = ( FHeader.Info[14] << 24 | FHeader.Info[15] << 16 | FHeader.Info[16] << 8 | FHeader.Info[17] );

					if ( 0 == (FHeader.MetaDataBlockHeader[1] & 0x80) ) // metadata block exists
					{
						iIndex = 0;
						do // read more metadata blocks if available
						{		  
							aMetaDataBlockHeader = r.ReadBytes(4);

							iIndex++; // metadatablock index
							iBlockLength = (aMetaDataBlockHeader[1] << 16 | aMetaDataBlockHeader[2] << 8 | aMetaDataBlockHeader[3]); //decode length
							if (iBlockLength <= 0) break; // can it be 0 ?

							iMetaType = (aMetaDataBlockHeader[0] & 0x7F); // decode metablock type

							if ( iMetaType == META_VORBIS_COMMENT )
							{  // read vorbis block
								FVCOffset = (int)fs.Position;
								FTagSize = iBlockLength;
								FVorbisIndex = iIndex;
								ReadTag(r, bSetTags); // set up fields
							}
							else 
							{
								if ((iMetaType == META_PADDING) && (! bPaddingFound) )  // we have padding block
								{ 
									FPadding = iBlockLength;                                            // if we find more skip & put them in metablock array
									FPaddingLast = ((aMetaDataBlockHeader[0] & 0x80) != 0);
									FPaddingIndex = iIndex;
									bPaddingFound = true;
									fs.Seek(FPadding, SeekOrigin.Current); // advance into file till next block or audio data start
								} 
								else // all other
								{ 
									if (iMetaType <= 5)   // is it a valid metablock ?
									{ 
										if (META_PADDING == iMetaType)  // set flag for fragmented padding blocks
										{ 
											FPaddingFragments = true;
										}
										AddMetaDataOther(aMetaDataBlockHeader, r, iBlockLength, iIndex);
									} 
									else 
									{
										FSamples = 0; //ops...
										break;
									}
								}
							}
						}
						while ( 0 == (aMetaDataBlockHeader[0] & 0x80) ); // while is not last flag ( first bit == 1 )
					}
				}
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR,e.Message);
				result = false;
			}
    
			if (FIsValid())  
			{
				FAudioOffset = (int)fs.Position;  // we need that to rebuild the file if nedeed
				FBitrate = Math.Round( ( (double)( FFileLength - FAudioOffset ) / 1000 ) * 8 / FGetDuration() ); //time to calculate average bitrate
			} 
			else 
			{
				result = false;
			}
    
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}

			return result;  
		}
Beispiel #9
0
		// ---------------------------------------------------------------------------

		private bool GetInfo(String FileName, ref FileInfo Info)
		{
			FileStream fs = null;
			BinaryReader Source = null;

			// Get info from file
			bool result = false;
  
			try
			{    
				// Set read-access and open file		
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);				
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				Info.FileSize = (int)fs.Length;
				Info.ID3v2Size = GetID3v2Size(Source);
				Source.BaseStream.Seek(Info.ID3v2Size, SeekOrigin.Begin);    

				Info.FPage.ID = Source.ReadChars(4);
				Info.FPage.StreamVersion = Source.ReadByte();
				Info.FPage.TypeFlag = Source.ReadByte();
				Info.FPage.AbsolutePosition = Source.ReadInt64();
				Info.FPage.Serial = Source.ReadInt32();
				Info.FPage.PageNumber = Source.ReadInt32();
				Info.FPage.Checksum = Source.ReadInt32();
				Info.FPage.Segments = Source.ReadByte();
				Info.FPage.LacingValues = Source.ReadBytes(0xFF);

				if ( Utils.StringEqualsArr(OGG_PAGE_ID,Info.FPage.ID) )
				{

					Source.BaseStream.Seek(Info.ID3v2Size + Info.FPage.Segments + 27, SeekOrigin.Begin);

					// Read Vorbis parameter header
					//Source.Read(Info.Parameters, 30);					
					Info.Parameters.ID = Source.ReadChars(7);
					Info.Parameters.BitstreamVersion = Source.ReadBytes(4);
					Info.Parameters.ChannelMode = Source.ReadByte();
					Info.Parameters.SampleRate = Source.ReadInt32();
					Info.Parameters.BitRateMaximal = Source.ReadInt32();
					Info.Parameters.BitRateNominal = Source.ReadInt32();
					Info.Parameters.BitRateMinimal = Source.ReadInt32();
					Info.Parameters.BlockSize = Source.ReadByte();
					Info.Parameters.StopFlag = Source.ReadByte();

					if ( Utils.StringEqualsArr(VORBIS_PARAMETERS_ID, Info.Parameters.ID) ) 
					{

						Info.SPagePos = (int)fs.Position;    

						Info.SPage.ID = Source.ReadChars(4);
						Info.SPage.StreamVersion = Source.ReadByte();
						Info.SPage.TypeFlag = Source.ReadByte();
						Info.SPage.AbsolutePosition = Source.ReadInt64();
						Info.SPage.Serial = Source.ReadInt32();
						Info.SPage.PageNumber = Source.ReadInt32();
						Info.SPage.Checksum = Source.ReadInt32();
						Info.SPage.Segments = Source.ReadByte();
						Info.SPage.LacingValues = Source.ReadBytes(0xFF);

						Source.BaseStream.Seek(Info.SPagePos + Info.SPage.Segments + 27, SeekOrigin.Begin);
		    
						Info.Tag.ID = Source.ReadChars(7);
						// Read Vorbis tag
						if ( Utils.StringEqualsArr(VORBIS_TAG_ID, Info.Tag.ID)) ReadTag(Source, ref Info); //# cast implicite douteux
		    
						// Get total number of samples
						Info.Samples = (int)GetSamples(Source);

						result = true;
					}
				}
			} 
			catch(Exception e)
			{
				//System.Console.WriteLine(e.StackTrace);	
				System.Console.WriteLine(e.Message);
				result = false;
			}
			
			if (fs != null)
			{				
				fs.Unlock(0,fs.Length);
				if (Source != null) Source.Close();				
			}

			return result;
		}
Beispiel #10
0
		// === PUBLIC METHODS ===

		public bool ReadFromFile(String fileName)
		{
			bool result = true;
			SPCHeader header = new SPCHeader();
			SPCExTags footer = new SPCExTags();

			FResetData();
			
			header.Reset();
			footer.Reset();

			FileStream fs = null;
			BinaryReader source = null;

			try
			{
				fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);

				if ( !readHeader(ref source, ref header) ) throw new Exception("Not a PSF file");

				// Reads the header tag
				if (SPCHeader.TAG_IN_HEADER == header.TagInHeader)
				{
					source.BaseStream.Seek(REGISTERS_LENGTH,SeekOrigin.Current);
					readHeaderTags(ref source);
				}

				// Reads extended tag
				if (fs.Length > SPC_RAW_LENGTH)
				{
					source.BaseStream.Seek(SPC_RAW_LENGTH,SeekOrigin.Begin);
					readExtendedData(ref source, ref footer);
					
					if (footer.Items.ContainsKey(XID6_ARTIST)) FArtist = (String)((ExtendedItem)footer.Items[XID6_ARTIST]).Data;
					if (footer.Items.ContainsKey(XID6_CMNTS)) FComment = (String)((ExtendedItem)footer.Items[XID6_CMNTS]).Data;
					if (footer.Items.ContainsKey(XID6_SONG)) FTitle = (String)((ExtendedItem)footer.Items[XID6_SONG]).Data;
					if (footer.Items.ContainsKey(XID6_COPY)) FYear = ((ExtendedItem)footer.Items[XID6_COPY]).Length.ToString();
					if (footer.Items.ContainsKey(XID6_TRACK)) FTrack = ((ExtendedItem)footer.Items[XID6_TRACK]).Length >> 8;
					if (footer.Items.ContainsKey(XID6_OST)) FAlbum = (String)((ExtendedItem)footer.Items[XID6_OST]).Data;
					if (("" == FAlbum) && (footer.Items.ContainsKey(XID6_GAME))) FAlbum = (String)((ExtendedItem)footer.Items[XID6_GAME]).Data;
					
					long ticks = 0;
					if (footer.Items.ContainsKey(XID6_LOOP)) ticks += Math.Min(XID6_MAXTICKS, (int)((ExtendedItem)footer.Items[XID6_LOOP]).Data);
					if (footer.Items.ContainsKey(XID6_LOOPX)) ticks = ticks * Math.Min(XID6_MAXLOOP, (int)((ExtendedItem)footer.Items[XID6_LOOPX]).Length );
					if (footer.Items.ContainsKey(XID6_INTRO)) ticks += Math.Min(XID6_MAXTICKS, (int)((ExtendedItem)footer.Items[XID6_INTRO]).Data);
					if (footer.Items.ContainsKey(XID6_END)) ticks += Math.Min(XID6_MAXTICKS, (int)((ExtendedItem)footer.Items[XID6_END]).Data);
					
					if (ticks > 0)
						FDuration = Math.Round( (double)ticks / XID6_TICKSSEC );
				}
			}
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
				result = false;
			}

			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}

			return result;
		}
Beispiel #11
0
		// === PUBLIC METHODS ===

		public bool ReadFromFile(String fileName)
		{
			bool result = true;
			PSFHeader header = new PSFHeader();
			PSFTag tag = new PSFTag();

			FResetData();
			
			header.Reset();
			tag.Reset();

			FileStream fs = null;
			BinaryReader source = null;

			try
			{
				fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);

				if ( !readHeader(ref source, ref header) ) throw new Exception("Not a PSF file");

				if (fs.Length > HEADER_LENGTH+header.CompressedProgramLength+header.ReservedAreaLength)
				{
					fs.Seek((long)(4+header.CompressedProgramLength+header.ReservedAreaLength),SeekOrigin.Current);
				
					if ( !readTag(ref source,ref tag) ) throw new Exception("Not a PSF tag");
				} 
			}
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
				result = false;
			}

			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}

			if (tag.tags.ContainsKey(TAG_GAME)) FAlbum = (String)tag.tags[TAG_GAME];
			if (tag.tags.ContainsKey(TAG_ARTIST)) FArtist = (String)tag.tags[TAG_ARTIST];
			if (tag.tags.ContainsKey(TAG_COMMENT)) FComment = (String)tag.tags[TAG_COMMENT];
			if (tag.tags.ContainsKey(TAG_TITLE)) FTitle = (String)tag.tags[TAG_TITLE];
			if (tag.tags.ContainsKey(TAG_YEAR)) FYear = (String)tag.tags[TAG_YEAR];
			if (tag.tags.ContainsKey(TAG_LENGTH)) 
			{
				FDuration = parsePSFDuration( (String)tag.tags[TAG_LENGTH] );				
			}
			if (tag.tags.ContainsKey(TAG_FADE)) 
			{
				FDuration += parsePSFDuration( (String)tag.tags[TAG_FADE] );				
			}

			return result;
		}
		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{    
			FileStream fs = null;
			BinaryReader source = null;
  
			char[] marker = new char[4];
  
			bool result = false;

			FResetData();
			FAPEtag.ReadFromFile(FileName);
			FTagSize = FAPEtag.Size;

			try
			{
				fs = new FileStream(FileName,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);

				FFileSize = fs.Length;
    	
				//read first bytes    	
				Array.Clear(marker,0,4);
    	
				marker = source.ReadChars(4);
				fs.Seek( 0, SeekOrigin.Begin );
				
				if ( Utils.StringEqualsArr("RIFF",marker) )
				{
					result = _ReadV3( source );
				}
				else 
				{
					if ( Utils.StringEqualsArr("wvpk",marker) )
					{
						result = _ReadV4( source );
					}
				}
    	
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
  
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}

			return result;
		}
Beispiel #13
0
        // UpFile-处理数据包
        private byte[] proUpFilePackage(EndPoint point, UnUdpEntity entity)
        {
            byte[] data = null;
            // 配置文件
            UnUdpEntity cofUPP = upFileConfigs.Find(t => t.HashCode == entity.HashCode);
            if (cofUPP == null)
            {
                cofUPP = new UnUdpEntity();
                cofUPP.HashCode = entity.HashCode;
                cofUPP.TotalPacks = entity.TotalPacks;
                cofUPP.TotalSize = entity.TotalSize;
                cofUPP.Extent = entity.Extent;
                cofUPP.SubSize = entity.SubSize;
                FileInfo cofFi = new FileInfo(UnUdpHelp.getUpFileTmpConfigPath(cofUPP.HashCode));
                FileInfo tmpFi = new FileInfo(UnUdpHelp.getUpFileReceivePath(cofUPP.HashCode));
                if (!cofFi.Exists)
                {
                    long[] ls = UnUdpHelp.waitUps(1, entity.TotalPacks, interval);
                    cofUPP.IntMin = ls[0];
                    cofUPP.IntMax = ls[1];
                    cofUPP.isReceived = new List<long>();
                    DirectoryInfo di = new DirectoryInfo(UnUdpHelp.getUpFileTmpDirectory(cofUPP.HashCode));
                    if (!di.Exists)
                    {
                        di.Create();
                    }
                    // 创建配置文件
                    using (FileStream fs = cofFi.Create())
                    {
                        byte[] prgBackBts = UnUdpHelp.assemblePackage(cofUPP);
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.Write(prgBackBts, 0, prgBackBts.Length);
                    }
                    // 创建临时文件
                    tmpFi.Create().Dispose();
                }
                else
                {
                    // 获得配置文件
                    using (FileStream fs = cofFi.OpenRead())
                    {
                        byte[] b = new byte[fs.Length];
                        fs.Read(b, 0, b.Length);
                        cofUPP = UnUdpHelp.analyzePackage(b);
                        if (cofUPP != null)
                        {
                            if (cofUPP.IntMin > 0)
                            {
                                cofUPP.UpCount = cofUPP.IntMin - 1;
                            }
                            else
                            {
                                cofUPP.UpCount = cofUPP.TotalPacks;
                            }
                        }
                    }
                }
                // 配置文件出错则删除重置
                if (cofUPP == null)
                {
                    cofFi.Delete();
                    return null;
                }
                ss.addUpTaskNum(1);
                upFileConfigs.Add(cofUPP);
            }
            // 唤醒时间
            cofUPP.WakeTimeStamp = UnDate.ticksSec();
            // 返回对象
            UnUdpEntity back = new UnUdpEntity();
            UnAttrRst rst = new UnAttrRst();

            switch (entity.Event.getUnUdpEveEnum())
            {
                case UnUdpEveEnum.upFileQuery:
                    back.IntMin = cofUPP.IntMin;
                    back.IntMax = cofUPP.IntMax;
                    back.TotalPacks = cofUPP.TotalPacks;
                    back.TotalSize = cofUPP.TotalSize;
                    back.UpCount = cofUPP.UpCount;
                    back.SubSize = cofUPP.SubSize;
                    back.Event = UnUdpEveEnum.upFileQueryBack.getText();

                    // 是否秒传
                    bool isMC = false;
                    // 开始上传
                    if (entity.State == 1)
                    {
                        if (intServer != null)
                        {
                            rst = intServer.upStart(point, entity);
                            if (rst != null)
                            {
                                cofUPP.State = rst.code;
                                back.State = cofUPP.State;
                                switch (cofUPP.State)
                                {
                                    case 1:// 传输完成
                                        cofUPP.UpCount = back.TotalPacks;
                                        back.UpCount = cofUPP.UpCount;
                                        cofUPP.WakeTimeStamp -=30;
                                        isMC = true;
                                        break;
                                    case -1:
                                    case -2:
                                        cofUPP.WakeTimeStamp -= 30;
                                        break;
                                }
                            }
                        }
                        // 默认处理
                        if (rst == null)
                        {
                            rst = new UnAttrRst();
                            rst.code = 0;
                            rst.msg = "传输中";
                        }
                    }

                    // 文件不是秒传,上传成功处理临时文件
                    if (!isMC && cofUPP.UpCount == cofUPP.TotalPacks)
                    {
                        cofUPP.State = 1;
                        back.State = cofUPP.State;
                        // 临时路径
                        string oldPath = UnUdpHelp.getUpFileReceivePath(cofUPP.HashCode);
                        if (intServer != null)
                        {
                            entity.TmpPath = oldPath;
                            rst = intServer.upSuccess(point, entity);
                            if (rst != null)
                            {
                                rst.code = 1;
                                rst.msg = "传输完成";
                            }
                        }
                        // 默认处理
                        if (rst == null)
                        {
                            // 转正式文件
                            string newPath = UnUdpHelp.getUpFileSavePath(cofUPP.HashCode, cofUPP.Extent);
                            UnFile.move(oldPath, newPath, true);
                            rst = new UnAttrRst();
                            rst.code = 1;
                            rst.msg = "上传成功";
                            rst.back = newPath;
                        }
                        cofUPP.WakeTimeStamp -= 25;
                    }

                    back.PackData = UnInit.getEncoding().GetBytes(UnXMMPXml.tToXml(typeof(UnAttrRst), rst));
                    data = UnUdpHelp.assemblePackage(back);
                    return data;
                case UnUdpEveEnum.upFilePackage:
                    // 在区间内且上传未完成
                    if (entity.PackNo >= cofUPP.IntMin && entity.PackNo <= cofUPP.IntMax && cofUPP.UpCount < cofUPP.TotalPacks)
                    {
                        // 是否已传
                        bool isHave = cofUPP.isReceived.Exists(t => t == entity.PackNo);
                        if (!isHave)
                        {
                            // 写入数据
                            using (FileStream fs = new FileStream(UnUdpHelp.getUpFileReceivePath(cofUPP.HashCode), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                fs.Lock(entity.PackOffset, entity.PackData.Length);
                                fs.Seek(entity.PackOffset, SeekOrigin.Begin);
                                fs.Write(entity.PackData, 0, entity.PackData.Length);
                                cofUPP.UpCount++;
                                cofUPP.isReceived.Add(entity.PackNo);

                                // 修改配置
                                if (cofUPP.UpCount == cofUPP.IntMax)
                                {
                                    long[] ls = UnUdpHelp.waitUps(cofUPP.IntMax + 1, entity.TotalPacks, interval);
                                    cofUPP.IntMin = ls[0];
                                    cofUPP.IntMax = ls[1];
                                    cofUPP.isReceived = new List<long>();
                                }
                                fs.Unlock(entity.PackOffset, entity.PackData.Length);
                            }
                        }
                    }

                    back.Event = UnUdpEveEnum.upFilePackageBack.getText();
                    back.PackNo = entity.PackNo;
                    back.UpCount = cofUPP.UpCount;
                    data = UnUdpHelp.assemblePackage(back);
                    return data;
            }
            return data;
        }
Beispiel #14
0
        /// <summary>
        /// 打开或创建文件。
        /// </summary>
        public void WriteFile(string content)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(FilePath);
            if (!dirInfo.Exists)
            {
                Directory.CreateDirectory(FilePath);
            }
            string fullFileName = FilePath + FileName;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fullFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                lock (this)
                {
                    byte[] buf;
                    long len;
                    try
                    {
                        buf = utf8.GetBytes(content);
                        len = fs.Length;
                        fs.Lock(0, len);
                        fs.Seek(0, SeekOrigin.End);
                        fs.Write(buf, 0, buf.Length);
                        fs.Unlock(0, len);
                        fs.Flush();
                        fs.Close();
                        fs = null;
                    }
                    catch (Exception er)
                    {
                        throw er;
                    }
                }
            }
            catch (Exception er)
            {
                throw er;
            }
        }
Beispiel #15
0
		// --------------------------------------------------------------------------- 

		// No explicit destructor in C#

		// --------------------------------------------------------------------------- 

		// Read data from file
		public bool ReadFromFile(String FileName)
		{		
			FileStream fs = null;
			BinaryReader Source = null;

			bool result = false;
	  
			FResetData();
			// At first search for tags, then try to recognize header type
			FID3v2.ReadFromFile(FileName);
			FID3v1.ReadFromFile(FileName);
			FAPEtag.ReadFromFile(FileName);
			try
			{
				fs = new FileStream(FileName, FileMode.Open);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				FFileSize = (int)fs.Length;
				FHeaderTypeID = FRecognizeHeaderType(Source);
				// Read header data
				if ( AAC_HEADER_TYPE_ADIF == FHeaderTypeID ) FReadADIF(Source);
				if ( AAC_HEADER_TYPE_ADTS == FHeaderTypeID ) FReadADTS(Source);

				result = true;
			}
			catch (Exception e)
			{
				result = false;
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()( Log.LV_ERROR, e.Message);
			}

			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				if (Source != null) Source.Close();				
			}

			return result;
		}
Beispiel #16
0
		/* -------------------------------------------------------------------------- */

		// No explicit destructors with C#

		/* -------------------------------------------------------------------------- */

		public bool ReadFromFile(String FileName)
		{
			FileStream fs = null;
			BinaryReader source = null;
  
			ushort signatureChunk;
			byte tehByte;

			bool result = false;
  
			FResetData();

			try
			{
				fs = new FileStream(FileName,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);
            
				signatureChunk = source.ReadUInt16();
            
				if ( /*0x0B77*/ 30475 == signatureChunk )
				{
					tehByte = 0;
		
					fs.Seek(2, SeekOrigin.Current);
					tehByte = source.ReadByte();

					FFileSize = fs.Length;
					FValid = true;

					switch (tehByte & 0xC0)
					{
						case 0: FSampleRate = 48000; break;
						case 0x40: FSampleRate = 44100; break;
						case 0x80: FSampleRate = 32000; break;
						default : FSampleRate = 0; break;
					}

					FBitrate = (ushort)BITRATES[(tehByte & 0x3F) >> 1];

					tehByte = 0;
	      	
					fs.Seek(1, SeekOrigin.Current);
					tehByte = source.ReadByte();

					switch (tehByte & 0xE0)
					{
						case 0: FChannels = 2; break;
						case 0x20: FChannels = 1; break;
						case 0x40: FChannels = 2; break;
						case 0x60: FChannels = 3; break;
						case 0x80: FChannels = 3; break;
						case 0xA0: FChannels = 4; break;
						case 0xC0: FChannels = 4; break;
						case 0xE0: FChannels = 5; break;
						default : FChannels = 0; break;
					}

					FBits = 16;
					FDuration = (double)FFileSize * 8 / 1000 / FBitrate;

					result = true;
				}
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
    
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				if (source != null) source.Close();
			}
  
			return result;
		}
Beispiel #17
0
        /// <summary>
        /// Causes a thread to be scheduled for execution.
        /// </summary>
        protected override void ExecuteTask()
        {
            string ver = SharpPcap.Version.VersionString;

            // Get the local processing folders
            DirectoryInfo captureDir = new DirectoryInfo(_captureToFolder);
            DirectoryInfo processDir = new DirectoryInfo(_processToFolder);
            DirectoryInfo outputDir = new DirectoryInfo(_statisticsToFolder);

            // Get the local drive for checking disk space
            DriveInfo volume = new DriveInfo(outputDir.Root.ToString());

            FileInfo pcapFile = null;
            string pcapFilename = "";
            string pcapFilter = "*.pcap";

            DateTime start = DateTime.Now;

            do
            {
                //Check if there are files if not wait 10 sec then check again
                do
                {
                    TimeSpan timer = DateTime.Now - start;
                    int seconds = (int)timer.TotalSeconds;
                    Console.WriteLine("-> {0} seconds to process.", seconds.ToString());
                    start = DateTime.Now;

                    // Null the file until we find one that is unlocked
                    pcapFile = null;
                    try
                    {
                        foreach (FileInfo p in captureDir.GetFiles(pcapFilter))
                        {
                            Console.WriteLine(p.FullName);

                            if (!this.Running) { break; }

                            // Check to see if the file is locked using a file stream and FileShare.None
                            // If the file is not locked, keep it locked for at least a second

                            FileStream fs = new FileStream(p.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                            fs.Lock(0, fs.Length);
                            System.Threading.Thread.Sleep(1000);

                            // Get the file a
                            pcapFile = p;
                            pcapFilename = processDir.FullName + "\\" + pcapFile.Name;
                            long NeededSpace = p.Length * 2; // Double for enough free space for one capture with room remaining

                            // Unlock and close
                            fs.Unlock(0, fs.Length);
                            fs.Close();

                            // Check available disk space
                            if (NeededSpace > volume.AvailableFreeSpace)
                            {
                                this.parentService.Log(EventLogEntryType.Error, 1, "The disk drive " + outputDir.Root.ToString() + " is too low on disk space to analyze packet capture statistics.");
                                this.parentService.Stop();
                                return;
                            }

                            // Move the file for processing
                            pcapFile.MoveTo(pcapFilename);
                            break;
                        }
                    }
                    catch (System.IO.IOException)
                    {
                        // The file selected is locked by another thread or process
                        pcapFile = null;
                    }
                    catch (Exception ex)
                    {
                        // Log any errors
                        this.parentService.Log(EventLogEntryType.Warning,
                            "{0} thread ({1}) error opening pcap file.\n{2}",
                            this.ThreadName,
                            this.ThreadId.ToString(),
                            ex.ToString());

                        pcapFile = null;
                    }

                    // If we have gotten this far, then no files are available or all files are locked
                    // Sleep the thread
                    if (!(pcapFile == null))
                        System.Threading.Thread.Sleep(10000);

                } while (pcapFile == null);

                parsePcap(pcapFilename, outputDir);

            } while (this.Running);

            // End the thread and return
            this.Stop();
        }
Beispiel #18
0
		void LockUnlock (long value)
		{
			using (FileStream fs = new FileStream (testfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) {
				fs.Lock (value - 1, 1);
				fs.Unlock (value - 1, 1);
				
				fs.Lock (0, value);
				fs.Unlock (0, value);
			}
		}
Beispiel #19
0
 private void UnlockDataStore(FileStream fs)
 {
     fs.Unlock(0, fs.Length);
 }
Beispiel #20
0
        public override void Process()
        {
            // save the List.xml in [temp-directory]\List\List_[SenderID].xml
            while (true)
            {
                try
                {
                    FileStream fs = new FileStream((Global.TempDirectory + @"\List\" + string.Format("List_{0}.xml", this.SenderPeer.ID)), FileMode.Create);

                    try { fs.Lock(0, fs.Length); }
                    catch { }

                    fs.Write(m_bytXmlBinary, 0, m_bytXmlBinary.Length);

                    try { fs.Unlock(0, fs.Length); }
                    catch { }

                    fs.Close();

                    break;
                }

                catch
                {
                    Thread.Sleep(1);
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// 写数据
        /// </summary>
        /// <param name="writer">FileStream对象</param>
        /// <param name="data">数据</param>
        /// <returns>true-成功;false-失败</returns>
        private bool Save(FileStream writer, string data)
        {
            if (writer == null || writer.Equals(null))
                return false;

            byte[] b = null;
            long len = 0;

            b = Utf8.GetBytes(data);
            len = writer.Length;
            try
            {
                writer.Lock(0, len);
                writer.Seek(0, SeekOrigin.End);
                writer.Write(b, 0, b.Length);
                writer.Unlock(0, len);
                writer.Flush();
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                try
                {
                    writer.Close();
                }
                catch (Exception Ex)
                {
                    throw Ex;
                }
            }

            return true;
        }
        private void StoreToFile(FileMode fileMode)
        {
            int writeBlock;
            int startIndex;
            const int SEP_LEN = 70;

            writeBlock = this.customInfo.Length + SEP_LEN;
            startIndex = 0;

            FileStream logFileStream = null;
            try
            {
                logFileStream = new FileStream(this.logFilePath, fileMode, FileAccess.Write);

                using (StreamWriter writer = new StreamWriter(logFileStream))
                {
                    logFileStream.Lock(startIndex, writeBlock);
                    writer.BaseStream.Seek(0, SeekOrigin.Current);
                    writer.Write(this.customInfo.ToString());
                    writer.Flush();
                    logFileStream.Unlock(startIndex, writeBlock);
                    logFileStream = null;
                }
            }
            finally
            {
                if (logFileStream != null)
                {
                    logFileStream.Close();
                }
            }
        }
Beispiel #23
0
		public void TestLock ()
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "TestLock";
			DeleteFile (path);

			FileStream stream = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite);

			stream.Write (new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, 10);
			stream.Close ();

			stream = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);

			stream.Lock (0, 5);

			FileStream stream2 = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

			byte[] bytes = new byte[5];
			try {
				stream2.Read (bytes, 0, 5);
				Assert.Fail ("#A1");
			} catch (Exception) {
				// Bug #71371: on MS.NET you get an IOException detailing a lock
				// Assert.AreEqual (typeof (IOException), e.GetType (), "#A2");
			}

			stream2.Seek (5, SeekOrigin.Begin);
			stream2.Read (bytes, 0, 5);

			Assert.AreEqual (5, bytes[0], "#B1");
			Assert.AreEqual (6, bytes[1], "#B2");
			Assert.AreEqual (7, bytes[2], "#B3");
			Assert.AreEqual (8, bytes[3], "#B4");
			Assert.AreEqual (9, bytes[4], "#B5");

			stream.Unlock (0, 5);
			stream2.Seek (0, SeekOrigin.Begin);
			stream2.Read (bytes, 0, 5);

			Assert.AreEqual (0, bytes[0], "#C1");
			Assert.AreEqual (1, bytes[1], "#C2");
			Assert.AreEqual (2, bytes[2], "#C3");
			Assert.AreEqual (3, bytes[3], "#C4");
			Assert.AreEqual (4, bytes[4], "#C5");

			stream.Close ();
			stream2.Close ();

			DeleteFile (path);
		}
Beispiel #24
0
		// ---------------------------------------------------------------------------

		bool AddToFile(String FileName, Stream TagData)
		{
			FileStream fs = null;
			BinaryWriter TargetFile = null;
			bool result;

			try
			{
				// Add tag data to file
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Write);
				fs.Lock(0,fs.Length); // Share Exclusive - originally, read denied
				TargetFile = new BinaryWriter(fs);

				TargetFile.BaseStream.Seek(0, SeekOrigin.End);
				TagData.Seek(0, SeekOrigin.Begin);
			
				byte[] bytes = new byte[TagData.Length];
				int numBytesToRead = (int) TagData.Length;
				int numBytesRead = 0;
				while (numBytesToRead > 0) 
				{
					// Read may return anything from 0 to numBytesToRead.
					int n = TagData.Read(bytes, numBytesRead, numBytesToRead);
					TargetFile.Write(bytes,0,n);

					// The end of the file is reached.
					if (0==n) break;
					numBytesRead += n;
					numBytesToRead -= n;				
				}
				//TargetFile.Write(TagData.ReadChars(TagData.Length));
				//FileData.CopyFrom(TagData, TagData.Size);
										
				result = true;
			} 
			catch (Exception e)
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				if (TargetFile != null) TargetFile.Close();
			}

			return result;
		}
        public int UnlockFile(String filename, long offset, long length, DokanFileInfo info)
        {
            string path = GetPath(filename);

            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
                fs.Unlock(offset, length);
                fs.Close();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("SetEndOfFile exception: {0}", e.Message);
                return -DokanNet.DOKAN_ERROR;
            }

            return DokanNet.DOKAN_SUCCESS;
        }
Beispiel #26
0
		// ---------------------------------------------------------------------------

		// No explicit destructors with C#

		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{
			FileStream fs = null;		
			BinaryReader Source = null;

			bool result = false;  

			try
			{
				// Reset data and search for file tag
				FResetData();
				FID3v1.ReadFromFile(FileName);
				FID3v2.ReadFromFile(FileName);
				FAPEtag.ReadFromFile(FileName);
				// Set read-access, open file and get file length
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				FFileLength = fs.Length;
				// Read header data
				Source.BaseStream.Seek(ID3v2.Size, SeekOrigin.Begin);
    
				//Source.Read(FHeader, sizeof(FHeader));

				FHeader.ID = Source.ReadChars(4);
				FHeader.Size = Source.ReadUInt32();
				FHeader.Length = Source.ReadUInt32();
				FHeader.HiLength = Source.ReadUInt16();
				FHeader.SampleType = Source.ReadByte();
				FHeader.ChannelMode = Source.ReadByte();
				FHeader.SampleRate = Source.ReadInt32();
				FHeader.EncoderID = Source.ReadUInt16();
				FHeader.CompressionID = Source.ReadByte();				

				if ( Utils.StringEqualsArr("OFR ",FHeader.ID) )
					result = true;
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				if (Source != null) Source.Close();
			}
			return result;
		}
Beispiel #27
0
 /// <inheritdoc />
 protected override void OnUnlockStream(System.IO.FileStream fileStream)
 {
     fileStream.Unlock(0, fileStream.Length);
 }
Beispiel #28
0
        private void SendGzippedFile(long length, FileStream f, long offset)
        {
            SendUnknownResponseHeader("Content-Encoding", "gzip");
            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress))
                {
                    f.Lock(offset, length);
                    f.Seek(offset, SeekOrigin.Begin);
                    const int readBuffLength = 4096;
                    byte[] buffer = new byte[readBuffLength];
                    int readed;
                    while ((readed = f.Read(buffer, 0, readBuffLength)) != 0)
                    {
                        gzip.Write(buffer, 0, readed);
                    }
                    f.Unlock(offset, length);
                    //Write some empty block
                    byte[] rn = Encoding.UTF8.GetBytes(Environment.NewLine);
                    for (int i = 0; i < 3; i++)
                    {
                        gzip.Write(rn, 0, rn.Length);
                    }

                    gzip.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
#if (ETAG)
					FileInfo finfo = new FileInfo(f.Name);
					string etag = string.Format("\"{0}.{1}\"", finfo.LastWriteTimeUtc.ToFileTimeUtc(), ms.Length);
                    SendUnknownResponseHeader("Etag", etag);
#endif
                    SendCalculatedContentLength(ms.Length);
                    SendResponseFromMemoryInternal(ms.GetBuffer(), (int)ms.Length);
                }
            }
        }
                public void TestLock()
                {
			string path = TempFolder + Path.DirectorySeparatorChar + "TestLock";
                	DeleteFile (path);

                	FileStream stream = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite);
                	                	
	               	stream.Write (new Byte [] {0,1,2,3,4,5,6,7,8,9,10}, 0, 10);                              	
                	stream.Close ();

                	stream = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);
                	
                	stream.Lock (0, 5);
                	
                	FileStream stream2 = new FileStream (path , FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                	
                	byte [] bytes = new byte [5];
                	try {                		
                		stream2.Read (bytes, 0, 5);
                		Fail ();
                	} catch (Exception e) {
                		
                		// locked
                		// AssertEquals ("test#01", typeof (IOException), e.GetType ());
				//
				// Moved into the previous test case.
                	}
               		                
                	stream2.Seek (5, SeekOrigin.Begin);
               		stream2.Read (bytes, 0, 5);
                	
                	AssertEquals ("test#02", 5, bytes [0]);
                	AssertEquals ("test#03", 6, bytes [1]);                	
                	AssertEquals ("test#04", 7, bytes [2]); 
                	AssertEquals ("test#05", 8, bytes [3]);
                	AssertEquals ("test#06", 9, bytes [4]);
                	
                	stream.Unlock (0,5);
                	stream2.Seek (0, SeekOrigin.Begin);	
               		stream2.Read (bytes, 0, 5);
                	
                	AssertEquals ("test#02", 0, bytes [0]);
                	AssertEquals ("test#03", 1, bytes [1]);                	
                	AssertEquals ("test#04", 2, bytes [2]); 
                	AssertEquals ("test#05", 3, bytes [3]);
                	AssertEquals ("test#06", 4, bytes [4]);
                	                	
                	stream.Close ();
                	stream2.Close ();
                	
                	DeleteFile (path);                		
                }
Beispiel #30
0
        // Store event information in a local file.
        private void StoreToFile(StringBuilder text, string filePath, FileMode mode)
        {
            int writeBlock;
            int startIndex;

            try
            {

                writeBlock = 256;
                startIndex = 0;

                // Open or create the local file
                // to store the event information.
                FileStream fs = new FileStream(filePath, mode, FileAccess.Write);

                // Lock the file for writing.
                fs.Lock(startIndex, writeBlock);

                // Create a stream writer
                StreamWriter writer = new StreamWriter(fs);

                // Set the file pointer to the current
                // position to keep adding data to it.
                // If you want to rewrite the file use
                // the following statement instead.
                // writer.BaseStream.Seek (0, SeekOrigin.Begin);
                writer.BaseStream.Seek(0, SeekOrigin.Current);

                //If the file already exists it must not
                // be write protected otherwise
                // the following write operation fails silently.
                writer.Write(text.ToString());

                // Update the underlying file
                writer.Flush();

                // Unlock the file for other processes.
                fs.Unlock(startIndex, writeBlock);

                // Close the stream writer and the underlying file
                writer.Close();

                fs.Close();
            }
            catch (Exception e)
            {
                throw new Exception("SampleEventProvider.StoreToFile: " + e.ToString());
            }
        }