当前位置: 首页>>代码示例>>C#>>正文


C# FileStream.Lock方法代码示例

本文整理汇总了C#中System.IO.FileStream.Lock方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.Lock方法的具体用法?C# FileStream.Lock怎么用?C# FileStream.Lock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileStream的用法示例。


在下文中一共展示了FileStream.Lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FileSystemExclusiveLock

        public FileSystemExclusiveLock(string pathToLock, ILog log)
        {
            EnsureTargetFile(pathToLock, log);

            var success = false;

            //Unfortunately this is the only filesystem locking api that .net exposes
            //You can P/Invoke into better ones but thats not cross-platform
            while (!success)
            {
                try
                {
                    _fileStream = new FileStream(pathToLock, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    // Oh and there's no async version!
                    _fileStream.Lock(0, 1);
                    success = true;
                }
                catch (IOException)
                {
                    success = false;
                    //Have I mentioned that I hate this algorithm?
                    //This basically just causes the thread to yield to the scheduler
                    //we'll be back here more than 1 tick from now
                    Thread.Sleep(TimeSpan.FromTicks(1));
                }
            }
        }
开发者ID:xenoputtss,项目名称:Rebus,代码行数:27,代码来源:FilesystemExclusiveLock.cs

示例2: loadClick

        public void loadClick(DateTime time)
        {
            // 储存到文件,比如20130203.xml
            string fileName = this.logFile;
            string today = time.ToString("yyyyMMdd");
            SerializableDictionary fileDatas = new SerializableDictionary();

            using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read))
            {
                stream.Lock(0, stream.Length);
                XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
                if (stream.Length != 0)
                {
                    fileDatas = (SerializableDictionary)serializer.Deserialize(stream);
                    if (!fileDatas.ContainsKey(today))
                    {
                        fileDatas[today] = new MouseState();
                    }
                }
                else
                {
                    fileDatas = new SerializableDictionary();
                    fileDatas[today] = new MouseState();
                }
                this.leftClickCount = fileDatas[today].leftClickCount;
                this.rightClickCount = fileDatas[today].rightClickCount;
                this.middleClickCount = fileDatas[today].middleClickCount;
            }
        }
开发者ID:jianfengye,项目名称:MouseMonitor,代码行数:29,代码来源:MouseState.cs

示例3: GetExclusiveAccess

        private static void GetExclusiveAccess(FileStream fs)
        {
            int i;

            for (i = 0; i < 10; i++) {
                try {
                    fs.Lock(0, 1);
                    return;
                } catch {
                    System.Threading.Thread.Sleep(2000);
                }
            }

            throw new Exception("cant get lock for sql recovery on file " + fs.Name);
        }
开发者ID:adrichal,项目名称:SQLinqenlot,代码行数:15,代码来源:FileOfObjects.cs

示例4: ExecuteFailsOnException

        public void ExecuteFailsOnException()
        {
            var copyFileAction = new CopyFileAction(Path.Combine(_sourceDirectory, "ExceptionFile.txt"), Path.Combine(_destinationDirectory, "ExceptionFile.txt"));
            using(StreamWriter s = File.CreateText(copyFileAction.Destination))
            {

            }
            using(FileStream fileStream = new FileStream(copyFileAction.Destination, 
                   FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
               {
                   UnicodeEncoding uniEncoding = new UnicodeEncoding();
                   fileStream.Write(uniEncoding.GetBytes("ABC"),0,3);
                   fileStream.Lock(0, 1);
                   Assert.That(copyFileAction.Execute() == false);

               }
            
        }
开发者ID:simon-knox,项目名称:SafeAndSound2014,代码行数:18,代码来源:CopyFileActionTests.cs

示例5: TryLockFile

 private static void TryLockFile(FileStream fileStream, long position, long length, int tryCount)
 {
     try
     {
         fileStream.Lock(position, length);
     }
     catch (IOException ex)
     {
         if (!ex.IsLockException())
         {
             throw ex;
         }
         if (tryCount >= 50)
         {
             throw new FileDBException("Database file is in lock for a long time");
         }
         Thread.Sleep((int) (tryCount * 50));
         TryLockFile(fileStream, position, length, ++tryCount);
     }
 }
开发者ID:mind0n,项目名称:hive,代码行数:20,代码来源:BinaryWriterExtensions.cs

示例6: TryLockFile

        private static void TryLockFile(FileStream fileStream, long position, long length, int tryCount)
        {
            try
            {
                fileStream.Lock(position, length);
            }
            catch (IOException ex)
            {
                if (ex.IsLockException())
                {
                    if (tryCount >= DELAY_TRY_LOCK_FILE)
                        throw new FileDBException("Database file is in lock for a long time");

                    Thread.Sleep(tryCount * DELAY_TRY_LOCK_FILE);

                    TryLockFile(fileStream, position, length, ++tryCount);
                }
                else
                    throw ex;
            }
        }
开发者ID:prepare,项目名称:FileDB,代码行数:21,代码来源:BinaryWriterExtensions.cs

示例7: FileInUse

 static bool FileInUse(string path,ref string __message)
 {
     try
     {
         //Just opening the file as open/create
         using (fs = new FileStream(path, FileMode.Open))
         {
             //If required we can check for read/write by using fs.CanRead or fs.CanWrite
             fs.Lock(0, int.MaxValue);
         }
         return false;
     }
     catch (IOException ex)
     {
         //check if message is for a File IO
         __message = ex.Message.ToString();
         if (__message.Contains("The process cannot access the file"))
             return true;
         else
             throw;
     }
 }
开发者ID:EdiCarlos,项目名称:MyPractices,代码行数:22,代码来源:Form1.cs

示例8: ReadFromFile

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

		// 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;
		}
开发者ID:bossaia,项目名称:alexandrialibrary,代码行数:89,代码来源:TTA.cs

示例9: Save

        /// <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;
        }
开发者ID:wudan330260402,项目名称:Danwu.Core,代码行数:46,代码来源:CommonLog.cs

示例10: ReadData

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

		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;
		}
开发者ID:bossaia,项目名称:alexandrialibrary,代码行数:55,代码来源:WMAfile.cs

示例11: LockDataStore

 private void LockDataStore(FileStream fs)
 {
     fs.Lock(0, fs.Length);
 }
开发者ID:greg-mitchell,项目名称:Folio,代码行数:4,代码来源:MainView.cs

示例12: StoreToFile

        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();
                }
            }
        }
开发者ID:adasescu,项目名称:cf-windows-extensions,代码行数:32,代码来源:LogFileWebEventProvider.cs

示例13: ReadFromFile

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

		// 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;
		}
开发者ID:bossaia,项目名称:alexandrialibrary,代码行数:57,代码来源:OptimFROG.cs

示例14: ReadFromFile

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

		// 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;
//.........这里部分代码省略.........
开发者ID:bossaia,项目名称:alexandrialibrary,代码行数:101,代码来源:Monkey.cs

示例15: udpProDownFileBack

        // 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);
//.........这里部分代码省略.........
开发者ID:xxgkgk,项目名称:UnifyNet,代码行数:101,代码来源:UnUdpClient.cs


注:本文中的System.IO.FileStream.Lock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。