Open() public method

public Open ( FileMode mode ) : FileStream
mode FileMode
return FileStream
Example #1
0
 public void SaveFile(string fileName, IList<Shape> shapes)
 {
     var fileInfo = new FileInfo(fileName);
     try
     {
         if (fileInfo.Exists)
         {
             using (var fileStream = fileInfo.Open(FileMode.Truncate, FileAccess.ReadWrite))
             {
                 SerializeAndSave(shapes, fileStream);
             }
         }
         else
         {
             using (var fileStream = fileInfo.Open(FileMode.CreateNew, FileAccess.ReadWrite))
             {
                 SerializeAndSave(shapes, fileStream);
             }
         }
     }
     catch (Exception exception)
     {
        ThrowMeaningfulException(exception, fileName);
     }
 }
Example #2
0
 public void DeleteAppVersionIndexEntry(Guid appKey)
 {
     var localAppIndexFile = new FileInfo(config.DeploymentDirectory + STR_LOCAL_APP_INDEX_FILE);
     string serialised;
     if (localAppIndexFile.Exists)
     {
         List<Plywood.Internal.EntityIndexEntry> index;
         using (var stream = localAppIndexFile.Open(FileMode.Open, FileAccess.Read))
         {
             index = Internal.Indexes.ParseIndex(stream);
         }
         if (index.Any(e => e.Key == appKey))
         {
             index.RemoveAll(e => e.Key == appKey);
             index.Sort(delegate(Internal.EntityIndexEntry a, Internal.EntityIndexEntry b)
             {
                 return string.Compare(a.Name, b.Name, true);
             });
             serialised = Internal.Indexes.SerialiseIndex(index);
             using (var stream = localAppIndexFile.Open(FileMode.Create, FileAccess.Write))
             {
                 var writer = new StreamWriter(stream);
                 writer.Write(serialised);
                 writer.Flush();
                 stream.Flush();
             }
         }
     }
 }
Example #3
0
 /// <summary>
 /// Creates a processor that corresponds to this command.
 /// </summary>
 /// <returns></returns>
 public override ProcessorBase CreateProcessor()
 {
     var outputFile = new FileInfo(this.File);
     if (outputFile.Exists)
     {
         return new ProcessorTarget(new PBFOsmStreamTarget(outputFile.Open(FileMode.Truncate)));
     }
     return new ProcessorTarget(new PBFOsmStreamTarget(outputFile.Open(FileMode.Create)));
 }
Example #4
0
 static void CreateFile()
 {
     FileInfo f = new FileInfo(filename);
     if (f.Exists)
     {
         Console.WriteLine("Файл уже существует. Пересоздать? yes/no");
         if (Console.ReadLine() == "yes")
             using (FileStream fs = f.Open(FileMode.Create)) { }
     }
     else
         using (FileStream fs = f.Open(FileMode.CreateNew)) { }
     Console.WriteLine("Готово!");
 }
 public void CreateOrAppendToFile(string fileLocation, Stream stream)
 {
     var sourcePath = Path.Combine(DebugConfig.LocalStoragePath, fileLocation);
     var fileInfo = new FileInfo(sourcePath);
     if (fileInfo.Exists)
     {
         using (var streamWrite = fileInfo.Open(FileMode.Append, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
     else
     {
         using (var streamWrite = fileInfo.Open(FileMode.Create, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
 }
Example #6
0
        public void Save(string fileName)
        {
            var file = new FileInfo(fileName);
            using (FileStream stream = file.Open(FileMode.Create, FileAccess.Write))
            {
                using (var writer = new BinaryWriter(stream, Encoding.Unicode))
                {
                    writer.Write(Encoding.ASCII.GetBytes("gufont"));

                    byte[] nameBytes = Encoding.UTF8.GetBytes(FontName);
                    writer.Write(nameBytes.Length);
                    writer.Write(nameBytes);

                    writer.Write((int)Style);
                    writer.Write(UnitsPerEm);
                    writer.Write(ascend);
                    writer.Write(descend);
                    writer.Write(lineGap);

                    writer.Write(glyphDictionary.Count);
                    foreach (var kvp in glyphDictionary)
                    {
                        writer.Write(kvp.Key);
                        writer.Write(kvp.Value);
                    }

                    writer.Write(glyphs.Length);
                    foreach (var glyph in glyphs)
                        glyph.Save(writer);
                }
            }
        }
Example #7
0
        private void AeroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            className = null;
            var info = new FileInfo(path);
            if (!info.Exists)
            {
                MessageBox.Show(string.Format("File \"{0}\" doesn't exist!", path), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
                return;
            }

            try
            {
                var buffer = info.Open(FileMode.Open).ReadToBuffer();
                var assembly = Assembly.Load(buffer);
                listTaskClasses.ItemsSource = from type in assembly.GetExportedTypes()
                                              where (from interf in type.GetInterfaces()
                                                     where interf == interfaceType
                                                     select interf).Count() > 0
                                              select type;

                textBoxAssembly.Text = assembly.FullName;
                textBoxLocalPath.Text = path;
            }
            catch (Exception err)
            {
                MessageBox.Show(string.Format("File \"{0}\" opening error:\n{1}", path, err), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
                return;
            }
        }
        public void SlowFileWriting(
            [Values(true, false)]bool contentChanges,
            [Values(FileAccess.ReadWrite, FileAccess.Write)]FileAccess access,
            [Values(FileShare.None, FileShare.ReadWrite, FileShare.Read, FileShare.Delete)]FileShare share)
        {
            int length = 10;
            this.ContentChangesActive = contentChanges;
            this.InitializeAndRunRepo(swallowExceptions: true);
            var file = new FileInfo(Path.Combine(this.localRootDir.FullName, "file"));
            using (var task = Task.Factory.StartNew(() => {
                using (var stream = file.Open(FileMode.CreateNew, access, share)) {
                    for (int i = 0; i < length; i++) {
                        Thread.Sleep(1000);
                        stream.WriteByte((byte)'0');
                    }
                }
            })) {
                while (!task.Wait(1000)) {
                    this.AddStartNextSyncEvent();
                    this.repo.Run();
                }

                this.AddStartNextSyncEvent();
                this.repo.Run();
            }

            Assert.That(this.localRootDir.GetFiles().Length, Is.EqualTo(1));
            Assert.That(this.remoteRootDir.GetChildren().TotalNumItems, Is.EqualTo(1));
            Assert.That(this.localRootDir.GetFiles().First().Length, Is.EqualTo(length));
            Assert.That((this.remoteRootDir.GetChildren().First() as IDocument).ContentStreamLength, Is.EqualTo(length));
        }
Example #9
0
 /// <summary>
 /// 下载文件
 /// </summary>
 /// <param name="FileFullPath">下载文件下载的完整路径及名称</param>
 public static void DownLoadFile(string FileFullPath)
 {
     if (!string.IsNullOrEmpty(FileFullPath) && FileExists(FileFullPath))
     {
         FileInfo fi = new FileInfo(FileFullPath);//文件信息
         FileFullPath = HttpUtility.UrlEncode(FileFullPath); //对文件名编码
         FileFullPath = FileFullPath.Replace("+", "%20"); //解决空格被编码为"+"号的问题
         HttpContext.Current.Response.Clear();
         HttpContext.Current.Response.ContentType = "application/octet-stream";
         HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath);
         HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //文件长度
         int chunkSize = 102400;//缓存区大小,可根据服务器性能及网络情况进行修改
         byte[] buffer = new byte[chunkSize]; //缓存区
         using (FileStream fs = fi.Open(FileMode.Open))  //打开一个文件流
         {
             while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) //如果没到文件尾并且客户在线
             {
                 int tmp = fs.Read(buffer, 0, chunkSize);//读取一块文件
                 if (tmp <= 0) break; //tmp=0说明文件已经读取完毕,则跳出循环
                 HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//向客户端传送一块文件
                 HttpContext.Current.Response.Flush();//保证缓存全部送出
                 Thread.Sleep(10);//主线程休息一下,以释放CPU
             }
         }
     }
 }
        protected override void OnStartup(StartupEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            Nullable<bool> result = dialog.ShowDialog();

            if (result != true)
            {
                Shutdown();
                return;
            }

            MachineType machineType;

            FileInfo fileInfo = new FileInfo(dialog.FileName);

            try
            {
                using (FileStream filestream = fileInfo.Open(FileMode.Open, FileAccess.Read))
                {
                    machineType = ReadMachineType(filestream);
                }
            }
            catch (PEHeaderNotFoundException error)
            {
                MessageBox.Show(error.Message);
                Shutdown();
                return;
            }

            DisplayMachineType(machineType);

            Shutdown();
        }
Example #11
0
        internal static bool IsLocked(string filePath)
        {
            if (filePath.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("filePath");
            }

            FileInfo file = new FileInfo(filePath);
            FileStream fileStream = null;

            try
            {
                fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }

            return false;
        }
Example #12
0
		public DisplayManager(PresentationPanel presentationPanel)
		{
			GL = GlobalWin.GL;
			this.presentationPanel = presentationPanel;
			GraphicsControl = this.presentationPanel.GraphicsControl;
			CR_GraphicsControl = GlobalWin.GLManager.GetContextForGraphicsControl(GraphicsControl);

			//it's sort of important for these to be initialized to something nonzero
			currEmuWidth = currEmuHeight = 1;

			if (GL is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)
				Renderer = new GuiRenderer(GL);
			else if (GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9)
				Renderer = new GuiRenderer(GL);
			else
				Renderer = new GDIPlusGuiRenderer((BizHawk.Bizware.BizwareGL.Drivers.GdiPlus.IGL_GdiPlus)GL);

			VideoTextureFrugalizer = new TextureFrugalizer(GL);

			ShaderChainFrugalizers = new RenderTargetFrugalizer[16]; //hacky hardcoded limit.. need some other way to manage these
			for (int i = 0; i < 16; i++)
			{
				ShaderChainFrugalizers[i] = new RenderTargetFrugalizer(GL);
			}

			using (var xml = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px.fnt"))
			using (var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px_0.png"))
				TheOneFont = new StringRenderer(GL, xml, tex);

			using (var gens = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.gens.ttf"))
				LoadCustomFont(gens);
			using (var fceux = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.fceux.ttf"))
				LoadCustomFont(fceux);

			if (GL is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK || GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9)
			{
				var fiHq2x = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/hq2x.cgp"));
				if (fiHq2x.Exists)
					using (var stream = fiHq2x.OpenRead())
						ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk"));
				var fiScanlines = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/BizScanlines.cgp"));
				if (fiScanlines.Exists)
					using (var stream = fiScanlines.OpenRead())
						ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk"));
				string bicubic_path = "Shaders/BizHawk/bicubic-fast.cgp";
				if(GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9)
					bicubic_path = "Shaders/BizHawk/bicubic-normal.cgp";
				var fiBicubic = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), bicubic_path));
				if (fiBicubic.Exists)
					using (var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
						ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk"));
			}

			LuaSurfaceSets["emu"] = new SwappableDisplaySurfaceSet();
			LuaSurfaceSets["native"] = new SwappableDisplaySurfaceSet();
			LuaSurfaceFrugalizers["emu"] = new TextureFrugalizer(GL);
			LuaSurfaceFrugalizers["native"] = new TextureFrugalizer(GL);

			RefreshUserShader();
		}
Example #13
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderid"></param>
        public void SetCurText(string orderid)
        {
            FileStream fileStream = null;
            StreamWriter writer = null;
            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(_fileName);
                if (!fileInfo.Exists)
                {
                    fileStream = fileInfo.Create();
                    writer = new StreamWriter(fileStream);
                }
                else
                {
                    fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write);
                    writer = new StreamWriter(fileStream);
                }
                writer.WriteLine(orderid);

            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
        public void loadItemDescription(ItemDescription details, String fileName)
        {
            FileInfo file = new FileInfo(dirPath.FullName + "\\" + fileName);
            if (!file.Exists)
            {
                throw new IOException("File does not exist");
            }
            FileStream s = file.Open(FileMode.Open, FileAccess.Read);
            StreamReader stream = new StreamReader(s, Encoding.Default);
            String content = stream.ReadToEnd();
            String[] splitted = content.Split(new string[] { "[","]\r\n","\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < splitted.Length - 1; i++)
            {
                if (splitted[i] == agape_rfid_desktop.Properties.Resources.descIT)
                {
                    details[Languages.IT].Description = splitted[++i];
                }
                else if (splitted[i] == agape_rfid_desktop.Properties.Resources.descEN)
                {
                    details[Languages.EN].Description = splitted[++i];
                }
                else if (splitted[i] == agape_rfid_desktop.Properties.Resources.valIT)
                {
                    details[Languages.IT].Values = splitted[++i];
                }
                else if (splitted[i] == agape_rfid_desktop.Properties.Resources.valEN)
                {
                    details[Languages.EN].Values = splitted[++i];
                }
            }

                // alla fine della fiera...close file stream
            s.Close();
        }
        public static void Main()
        {
            string fileName = @"enumtest.txt";
            FileInfo file = new FileInfo(fileName);
            file.Open(FileMode.Create).Close();

            FileAttributes startingAttributes =
                file.Attributes;

            file.Attributes = FileAttributes.Hidden |
                FileAttributes.ReadOnly;

            Console.WriteLine("\"{0}\" outputs as \"{1}\"",
                file.Attributes.ToString().Replace(",", " |"),
                file.Attributes);

            FileAttributes attributes =
                (FileAttributes)Enum.Parse(typeof(FileAttributes),
                file.Attributes.ToString());

            Console.WriteLine(attributes);

            File.SetAttributes(fileName,
                startingAttributes);
            file.Delete();
        }
Example #16
0
 internal static void ProcessMessageQueue()
 {
     Monitor.Enter(_lock);
     if (_messages.Count > 0)
     {
         if (!new DirectoryInfo(Settings.LogPath).Exists)
         {
             string cur = "";
             foreach (string str in Settings.LogPath.Split(Path.DirectorySeparatorChar))
             {
                 cur += str;
                 if (!new DirectoryInfo(cur).Exists)
                     new DirectoryInfo(cur).Create();
                 cur += Path.DirectorySeparatorChar;
             }
         }
         FileInfo fi = new FileInfo(Settings.LogPath + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
         StreamWriter sw = new StreamWriter(fi.Open(FileMode.Append, FileAccess.Write, FileShare.Read));
         for (int x = 0; x < MESSAGE_WRITE_COUNT; x++)
         {
             if (_messages.Count == 0)
                 break;
             sw.WriteLine(_messages.Dequeue());
         }
         sw.Flush();
         sw.Close();
     }
     Monitor.Exit(_lock);
 }
Example #17
0
		public static void CreateModFile( string ckDir, Mod mod )
		{
			FileInfo mpath = new FileInfo( ckDir + @"/mod/" + mod.ModFile );
			StreamWriter mw = new StreamWriter( mpath.Open( FileMode.Create, FileAccess.Write ), Encoding.GetEncoding( 1252 ) );

			mw.WriteLine( "name = \"" + mod.Name + "\"" );

			mw.WriteLine( "path = \"" + mod.Path + "\"" );

			mw.WriteLine();

			foreach( string e in mod.Extends )
				mw.WriteLine( "extend = \"" + e + "\"" );

			foreach( string e in mod.Replaces )
				mw.WriteLine( "replace_path = \"" + e + "\"" );

			if( mod.Dependencies.Count >= 0 )
			{
				mw.Write( "dependencies = {" );
				foreach( string s in mod.Dependencies )
					mw.Write( "\"" + s + "\" " );
				mw.WriteLine( "}" );
			}

			mw.Dispose();
		}
Example #18
0
        private static FileLog fLog = new FileLog(); //the file log

        #endregion Fields

        #region Methods

        /// <summary>
        /// Checks if a file is still being used (hasn't been completely transfered to the folder)
        /// </summary>
        /// <param name="path">The file to check</param>
        /// <returns><c>True</c> if the file is being used, <c>False</c> if now</returns>
        public static bool FileIsUsed(string path)
        {
            FileStream stream = null;

            string name = null;

            try
            {
                FileInfo fi = new FileInfo(path);
                name = fi.Name;
                stream = fi.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch
            {
                if (name != null)
                    Log.Write(l.Debug, "File {0} is locked: True", name);
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            if (name != null)
                Log.Write(l.Debug, "File {0} is locked: False", name);
            return false;
        }
Example #19
0
        public IDisposable Connect(IDataConsumer channel)
        {
            var fileInfo = new FileInfo(_filepath);
            using(FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read)) {
                var buffer = new byte[fileInfo.Length];
                fileStream.Read(buffer, 0, (int) fileInfo.Length);
                int length = (int) fileInfo.Length;
                int offset = 0;

                if(_requestHeaders.ContainsKey(HttpRequestHeader.Range.ToString())) {
                    string range = _requestHeaders[HttpRequestHeader.Range.ToString()];
                    Regex rangeEx = new Regex(@"bytes=([\d]*)-([\d]*)");
                    if(rangeEx.IsMatch(range)) {
                        int from = Convert.ToInt32(rangeEx.Match(range).Groups[1].Value);
                        int to = Convert.ToInt32(rangeEx.Match(range).Groups[2].Value);
                        offset = from;
                        length = (to - from) +1;
                    }
                }
                ArraySegment<byte> data = new ArraySegment<byte>(buffer, offset, length);
                channel.OnData(data, null);

                _log.DebugFormat("Wrote {0} bytes to buffer", data.Array.Length);
                channel.OnEnd();
                return null;
            }
        }
        private void WriteToLogFile(string message, bool useWriteLine)
        {
            try
            {
                FileInfo file = new FileInfo(this.FullName);
                using (Stream stream = file.Open(FileMode.Append, FileAccess.Write, FileShare.Write | FileShare.ReadWrite | FileShare.Delete))
                {
                    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                    {
                        stream.Position = stream.Length;

                        if (useWriteLine)
                        {
                            writer.WriteLine(message);
                        }
                        else
                        {
                            writer.Write(message);
                        }

                        writer.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine(ex.ToString());
            }
        }
Example #21
0
 public static void WriteEntryTo(this IReader reader, FileInfo filePath)
 {
     using (Stream stream = filePath.Open(FileMode.Create))
     {
         reader.WriteEntryTo(stream);
     }
 }
		protected override bool Execute()
		{
			string path = Path.Combine( m_options.Data.MyDocsDir.FullName, m_options.Mod.Path );
			path = Path.Combine( path, "history/titles" ).Replace( '\\', '/' );
			if( !Directory.Exists( path ) )
				Directory.CreateDirectory( path );

			path = Path.Combine( m_options.Data.MyDocsDir.FullName, m_options.Mod.Path );
			path = Path.Combine( path, "history/provinces" ).Replace( '\\', '/' );
			if( !Directory.Exists( path ) )
				Directory.CreateDirectory( path );

			path = Path.Combine( m_options.Data.MyDocsDir.FullName, m_options.Mod.Path );
			path = Path.Combine( path, "history/characters/KAChars.txt" ).Replace( '\\', '/' );
			FileInfo charFile = new FileInfo( path );
			if( !charFile.Directory.Exists )
				charFile.Directory.Create();

			StreamWriter charWriter = new StreamWriter( charFile.Open( FileMode.Create, FileAccess.Write ),
														Encoding.GetEncoding( 1252 ) );

			bool ret = CreateHistory( charWriter );
			if( ret )
			{
				ret = CreateRulesetCharacters( charWriter );
			}
			charWriter.Close();

			SaveProvinceHistory();
			return ret;
		}
Example #23
0
    public void WriteLog(string sErrMsg)
    {
        try
            {
                string sFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog.txt";
                System.IO.FileInfo objFileInfo = new System.IO.FileInfo(sFileName);
                if (!objFileInfo.Exists)
                    objFileInfo.Create();

                if (objFileInfo.Length > 10485760)
                {
                    string str_number = Guid.NewGuid().ToString();
                    string newFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog\\" + str_number + "ErrorLog.txt";
                    objFileInfo.CopyTo(newFile);
                    objFileInfo.Delete();
                }

                string sPathName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "//ErrorLog.txt";//ConfigurationSettings.AppSettings["LogFileName"];

                System.IO.FileStream objFileStream = objFileInfo.Open(System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objFileStream);
                objWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                objWriter.WriteLine("Error Occured at " + DateTime.Now.ToLongDateString() + " : " + DateTime.Now.ToLongTimeString());
                objWriter.WriteLine(sErrMsg);
                objWriter.WriteLine("----------------------------------------------------------------------");
                objWriter.Close();
            }
            catch { }
    }
 internal FileInfoRarArchiveVolume(FileInfo fileInfo, string password, Options options)
     : base(StreamingMode.Seekable, /*fileInfo.OpenRead()*/fileInfo.Open(FileMode.Open, FileAccess.Read), password, FixOptions(options))
 {
     FileInfo = fileInfo;
     //FileParts = base.GetVolumeFileParts().ToReadOnly();
     FileParts =Utility.ToReadOnly<RarFilePart>( base.GetVolumeFileParts());
 }
Example #25
0
		/// <summary>
		/// Checking is a file locked for reading or not
		/// </summary>
		/// <param name="filePath">File path</param>
		/// <returns></returns>
		public static bool IsFileLockedForRead(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
				throw new ArgumentNullException("filePath");

			if (!FileSystem.File.Exists(filePath))
				throw new FileNotFoundException("File not found: " + filePath);

			var file = new FileInfo(filePath);
			FileStream stream = null;

			try
			{
				stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
			}
			catch (IOException)
			{
				//the file is unavailable because it is:
				//still being written to
				//or being processed by another thread
				//or does not exist (has already been processed)
				return true;
			}
			finally
			{
				if (stream != null)
					stream.Close();
			}

			//file is not locked
			return false;
		}
Example #26
0
        public static bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;

            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }

            //file is not locked
            return false;
        }
Example #27
0
        // Constructor
        /// <summary>
        /// Open a profile (create if not exist) and load it.
        /// </summary>
        /// <param name="profileDirectory">The root directory of the profile</param>
        public CraftitudeProfile(DirectoryInfo profileDirectory)
        {
            Directory = profileDirectory;

            _craftitudeDirectory = Directory.CreateSubdirectory("craftitude");
            _craftitudeDirectory.CreateSubdirectory("repositories"); // repository package lists
            _craftitudeDirectory.CreateSubdirectory("packages"); // cached package setups

            _bsonFile = _craftitudeDirectory.GetFile("profile.bson");

            if (!_bsonFile.Exists)
            {
                ProfileInfo = new ProfileInfo();
            }
            else
            {
                using (FileStream bsonStream = _bsonFile.Open(FileMode.OpenOrCreate))
                {
                    using (var bsonReader = new BsonReader(bsonStream))
                    {
                        var jsonSerializer = new JsonSerializer();
                        ProfileInfo = jsonSerializer.Deserialize<ProfileInfo>(bsonReader) ?? new ProfileInfo();
                    }
                }
            }
        }
Example #28
0
        public override void OnComplete()
        {
            var path = GetFilePathFromRequest();
            var file = new FileInfo( path );
            var fileType = Response.GetContentTypeFromPath( path );

            Console.WriteLine( path );
            Response
                .Begin( HttpStatus.Ok, headers => headers
                    .AcceptRanges( "bytes" )
                    .ContentLength( file.Length )
                    .ContentType( fileType )
                    .Date( DateTime.UtcNow )
                    .LastModified( file.LastWriteTimeUtc )
                    .Server( "hyperstack" ));

            var bytes = new byte[file.Length];
            using( var handle = file.Open( FileMode.Open, FileAccess.Read, FileShare.Read ) )
            {
                var buffer = new byte[8*1024];
                var read = 0;
                var total = 0;
                while( ( read = handle.Read( buffer, 0, buffer.Length ) ) > 0 )
                {
                    Buffer.BlockCopy( buffer, 0, bytes, total, read );
                    total += read;
                }
            }
            Response.AppendToBody( bytes );
            Response.End();
        }
        Stream IPscxFileHandler.OpenWrite(string filePath, bool noClobber, bool force, bool terminateOnError)
        {
            try
            {
                FileInfo file = new FileInfo(filePath);
                FileMode mode = noClobber ? FileMode.CreateNew : FileMode.Create;

                if (force && !noClobber && file.Exists && file.IsReadOnly)
                {
                    return new ResetReadOnlyOnDisposeStream(file);
                }

                return file.Open(mode, FileAccess.Write);
            }
            catch (IOException exc)
            {
                ErrorHandler.HandleFileAlreadyExistsError(terminateOnError, filePath, exc);
            }
            catch (Exception exc)
            {
                ErrorHandler.HandleFileError(terminateOnError, filePath, exc);
            }

            return null;
        }
        public void Can_handle_truncated_start_transaction_seperator()
        {
            var txLogInfo = new FileInfo(Path.Combine(path, "transaction.log"));

            using (var queue = new PersistentQueue(path)
            {
                // avoid auto tx log trimming
                TrimTransactionLogOnDispose = false
            })
            {
                using (var session = queue.OpenSession())
                {
                    for (int j = 0; j < 20; j++)
                    {
                        session.Enqueue(BitConverter.GetBytes(j));
                        session.Flush();
                    }
                }
            }

            using (var txLog = txLogInfo.Open(FileMode.Open))
            {
                txLog.SetLength(5);// corrupt last transaction
                txLog.Flush();
            }

            using (var queue = new PersistentQueue(path))
            {
                using (var session = queue.OpenSession())
                {
                    Assert.IsNull(session.Dequeue());// the last transaction was corrupted
                    session.Flush();
                }
            }
        }