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); } }
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(); } } } }
/// <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))); }
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); } }
/// <summary> /// Open and reads the specified file, parsing it into a <see cref="ProjectInfp"/> instance. /// </summary> /// <param name="fileName">The file to read.</param> /// <returns>The <see cref="ProjectInfo"/> object which the file was parsed into.</returns> public static ProjectInfo Open(string fileName) { if (xmlSerializer == null) { xmlSerializer = new XmlSerializer(typeof(ProjectInfo)); } var fileInfo = new System.IO.FileInfo(fileName); using (var stream = fileInfo.Open(System.IO.FileMode.Open)) { var deserialized = xmlSerializer.Deserialize(stream) as ProjectInfo; if (deserialized != null) { deserialized.ProjectFile = fileInfo; if (string.IsNullOrEmpty(deserialized.OutputFileName)) { deserialized.OutputFileName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name); } deserialized.OnOpen(); return(deserialized); } } // failover return(null); }
/// <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(); } } }
/// <summary> /// 写入日志 /// </summary> /// <param name="message"></param> public static void Write(string message) { var dt = DateTime.Now; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); } var filename = dt.ToString("yyyy-MM-dd") + ".txt"; var logFile = Path.Combine(logDirectory, filename); System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss")); writer.WriteLine(message); writer.WriteLine(); //释放资源 writer.Dispose(); fileStream.Dispose(); }
/// <summary> /// 从指定文件读取二进制数据,返回获得的字节数组,若文件不存在或读取失败则返回空引用 /// </summary> /// <param name="strFile">文件名</param> /// <returns>获得字节数组,若读取失败则返回空引用</returns> public static byte[] LoadBinaryFile(string strFile) { try { if (strFile != null && System.IO.File.Exists(strFile)) { System.IO.FileInfo info = new System.IO.FileInfo(strFile); if (info.Length == 0) { return(null); } using (System.IO.FileStream myStream = info.Open( System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] byts = new byte[myStream.Length]; myStream.Read(byts, 0, byts.Length); myStream.Close(); return(byts); } } } catch { } return(null); } //public static byte[] LoadBinaryFile( string strFile )
public void log(string info, string fileName) { logFile = fileName; CreateDirectory(logFile); try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine(DateTime.Now + ": " + info); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } }
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 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; }
/// <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; }
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; }
/// <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 } } } }
//Usage //Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); //log.log(basePath); public void log(string info) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream, Encoding.UTF8); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream, Encoding.UTF8); } writer.WriteLine(DateTime.Now + ": " + info); //writer.WriteLine("----------------------------------"); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } }
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(); }
public StreamInfo <DateTime> DownloadProfileImage(int userId, string filePath) { //do somthing var stream = new StreamInfo <DateTime>(); if (!File.Exists(filePath)) { //return error when want for example file not found stream.Status = System.Net.HttpStatusCode.NotFound; return(stream); } var file = new System.IO.FileInfo(filePath); stream.Stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //length is important stream.Length = file.Length; //your result data stream.Data = file.LastWriteTime; OperationContext.Current.HttpClient.ResponseHeaders.Add("content-disposition", ("attachment; filename=" + file.Name).Split(',')); OperationContext.Current.HttpClient.ResponseHeaders.Add("Content-Type", file.Extension); return(stream); }
public IEnumerator TestRecord() { var go = new GameObject("RealSenseDevice", typeof(RealSenseDevice)); var rs = go.GetComponent <RealSenseDevice>(); go.SetActive(false); rs.processMode = RealSenseDevice.ProcessMode.UnityThread; rs.DeviceConfiguration.mode = RealSenseConfiguration.Mode.Record; var path = "D:/test.bag"; rs.DeviceConfiguration.RecordPath = path; go.SetActive(true); yield return(new WaitForSeconds(2f)); GameObject.Destroy(go); yield return(null); Assert.That(go == null); rs = null; // GC.Collect(); // GC.WaitForPendingFinalizers(); var fi = new System.IO.FileInfo(path); fi.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read); Assert.True(fi.Exists); Assert.Greater(fi.Length, 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(); }
private System.IO.FileStream NextLogStream() { if (null == _fileFinder) { throw new ObjectDisposedException("PendingCommandsEnumerator"); } CloseCurrentStream(); while (true) { System.IO.FileInfo nextLog = _fileFinder.NextPendingLog(); if (nextLog.Exists) { if (nextLog.Length > 0) { // Open the log file with // FileShare.ReadWrite // because the crashed prevalence engine might // not have closed it // TODO: Is this really necessary/desired? return(nextLog.Open( FileMode.Open, FileAccess.Read, FileShare.ReadWrite )); } } else { break; } } return(null); }
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()); }
public void log(string info) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.logFile); if (!fileInfo.Exists) { this.fileStream = fileInfo.Create(); this.writer = new StreamWriter(this.fileStream); } else { this.fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); this.writer = new StreamWriter(this.fileStream); } this.writer.WriteLine(info); } finally { if (this.writer != null) { this.writer.Close(); this.writer.Dispose(); this.fileStream.Close(); this.fileStream.Dispose(); } } }
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 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(); }
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 { } }
/// <summary> /// Log日志写入本地文件 /// </summary> /// <param name="info"></param> public void LogWrite(string Remarks, string info) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(_FilePath); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine(DateTime.Now + "--类型:" + Remarks + "---->" + "\r\n描述:" + info); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } }
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); }
static bool FileAvailable(string path) { if (!File.Exists(path)) { return(false); } FileInfo file = new System.IO.FileInfo(path); FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None); } catch (IOException) { // Can be either: // - file is processed by another thread // - file is still being written to // - file does not really exist yet return(false); } finally { if (stream != null) { stream.Close(); } } return(true); }
public static byte[] ReadAllBytes(this System.IO.FileInfo fileinfo) { if (fileinfo == null) { throw new System.ArgumentNullException("fileinfo"); } byte[] array; using (System.IO.FileStream fileStream = fileinfo.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { int num = 0; long length = fileStream.Length; if (length > 2147483647L) { throw new System.IO.IOException("IO.IO_FileTooLong2GB"); } int i = (int)length; array = new byte[i]; while (i > 0) { int num2 = fileStream.Read(array, num, i); if (num2 == 0) { throw new System.IO.EndOfStreamException("IO.EOF_ReadBeyondEOF"); } num += num2; i -= num2; } } return(array); }
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(); }
// 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(); } } } }
public void log(string info, string fullPath) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullPath); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine("Time:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); writer.WriteLine(info); writer.WriteLine("----------------------------------"); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } }
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; }
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()); } }
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; }
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)); }
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); } } }
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(); }
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 static void WriteEntryTo(this IReader reader, FileInfo filePath) { using (Stream stream = filePath.Open(FileMode.Create)) { reader.WriteEntryTo(stream); } }
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(); }
protected Boolean IsFileLocked(string filepath) { System.IO.FileInfo file = new System.IO.FileInfo(filepath); FileStream stream = null; try { //Don't change FileAccess to ReadWrite, //because if a file is in readOnly, it fails. 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); }
/*public void write(string info) * { * try * { * System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile); * if (!fileInfo.Exists) * { * fileStream = fileInfo.Create(); * writer = new StreamWriter(fileStream); * } * else * { * fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); * writer = new StreamWriter(fileStream); * } * writer.WriteLine(DateTime.Now + ": " + info); * writer.WriteLine("----------------------------------"); * } * finally * { * if (writer != null) * { * writer.Close(); * writer.Dispose(); * fileStream.Close(); * fileStream.Dispose(); * } * } * }*/ public static void write(string info, int level_local = 1) { if (level_local > level) { return; } lock (locker) { try { string FileName = Process.GetCurrentProcess().MainModule.FileName; string FilePath = System.IO.Path.GetDirectoryName(FileName); string sFilePath = FilePath + "\\log"; string fileName = sFilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; DirectoryInfo directoryInfo = Directory.GetParent(fileName); if (!directoryInfo.Exists) { directoryInfo.Create(); } System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } string strLog = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + info; writer.WriteLine(strLog); if (Event_ShowLog != null) { Event_ShowLog(strLog, null); } //writer.WriteLine("----------------------------------"); } catch (Exception ex) { } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } }
private void SaveFile(System.IO.FileInfo file, string content) { var tempContent = (new ASCIIEncoding()).GetBytes(content); new DirectoryInfo(file.DirectoryName).Create(); using (FileStream Writer = file.Open(FileMode.Open, FileAccess.Write)) { Writer.Write(tempContent, 0, tempContent.Length); } }
public HttpFile(string name, string filePath) { this.Name = name; var file = new System.IO.FileInfo(filePath); this.FileName = file.Name; this.ResponseStream = file.Open(FileMode.Open, FileAccess.Read); this.TotalBytesSize = file.Length; }
/// <summary> /// Writes log message /// </summary> /// <param name="logMessage">message to log</param> public void writeLog(String logMessage) { System.IO.FileStream fileStream = null; System.IO.StreamWriter sr = null; try { if (debug) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFolder); if (fileInfo.Exists && (fileInfo.Length + logMessage.Length) <= maxFileSize) { sr = fileInfo.AppendText(); } else { if (fileInfo.Exists) { DateTime dt = DateTime.Now; fileInfo.CopyTo(logFolder + "_" + dt.Hour + "_" + dt.Minute + "_" + dt.Second, true); fileStream = fileInfo.Open(FileMode.Truncate); fileStream.Close(); } fileStream = fileInfo.Open(System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); sr = new System.IO.StreamWriter(fileStream); } sr.WriteLine(logMessage); } } finally { if (sr != null) { sr.Close(); } if (fileStream != null) { fileStream.Close(); } } }
/// <summary> /// 将文件读取到字节流中 /// </summary> /// <param name="filePath">文件的绝对路径</param> /// <returns></returns> public static byte[] ReadToBytes(string filePath) { if (!File.Exists(filePath)) { return(null); } FileInfo fileInfo = new FileInfo(filePath); int fileSize = (int)fileInfo.Length; using (BinaryReader reader = new BinaryReader(fileInfo.Open(FileMode.Open))) { return(reader.ReadBytes(fileSize)); } }
/// <summary> /// 将文件读取到字节流中 /// </summary> /// <param name="fileInfo">文件信息</param> /// <returns></returns> public static byte[] ReadToBytes(FileInfo fileInfo) { if (fileInfo == null) { return(null); } int fileSize = (int)fileInfo.Length; using (var reader = new BinaryReader(fileInfo.Open(FileMode.Open))) { return(reader.ReadBytes(fileSize)); } }
public StoreCloudItem UploadFile(StoreCloud storeCloud, string VirtualPath, System.IO.FileInfo Fichier, string newFileName = null) { if (string.IsNullOrWhiteSpace(VirtualPath)) { VirtualPath = "/"; } VirtualPath = ValidateVirtualPath(VirtualPath); System.IO.Stream fstream = Fichier.Open(System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); if (string.IsNullOrWhiteSpace(newFileName)) { newFileName = Fichier.Name; } return(this.UploadFile(storeCloud, VirtualPath, fstream, newFileName)); }
public static string ReturnMD5Code(string FilePath) { #if !PCL try { #if WINDOWS_PHONE_APP var _file = Windows.Storage.StorageFile.GetFileFromPathAsync(FilePath).GetResults(); if (_file != null) #else var _file = new System.IO.FileInfo(FilePath); if (_file.Exists) #endif { var _md5 = Md5.Create(); #if WINDOWS_PHONE_APP using (var _reader = new System.IO.BinaryReader(_file.OpenStreamForReadAsync().Result)) #else using (var _reader = new System.IO.BinaryReader(_file.Open(FileMode.Open))) #endif { var _buffer = new byte[_reader.BaseStream.Length]; _reader.Read(_buffer, 0, _buffer.Length); #if !WINDOWS_PHONE_APP _reader.Close(); #endif var _hash = _md5.ComputeHash(_buffer); var _ret = new System.Text.StringBuilder(); for (int i = 0; i < _hash.Length; i++) { _ret.Append(_hash[i].ToString("X2")); } return(_ret.ToString()); } } else { return(""); } } catch (Exception ex) { return(""); } #else return(""); #endif }
public override System.IO.Stream Open(string filename, bool readOnly) { Stream strm = null; SafeDirectoryChange(_basePath, () => { if (File.Exists(_basePath + filename)) { System.IO.FileInfo fi = new System.IO.FileInfo(_basePath + filename); strm = (Stream)fi.Open(FileMode.Open, readOnly ? FileAccess.Read : FileAccess.ReadWrite); } }); return(strm); }
/// <summary> /// Serializes a <see cref="ProjectInfo"/> object and saving the output to <paramref name="file"/>. /// </summary> /// <param name="project">The project to save.</param> /// <param name="file">The file to save the output to.</param> public static void SaveAs(ProjectInfo project, System.IO.FileInfo file) { if (project == null) { throw new ArgumentNullException("project"); } if (file == null) { throw new ArgumentNullException("file"); } using (var stream = file.Open(System.IO.FileMode.Create)) { Serialize(project, stream); } }
/// <summary> /// 将文件读取到缓冲区中 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static byte[] FileToBytes(string filePath) { //获取文件的大小 int fileSize = GetFileSize(filePath); //创建一个临时缓冲区 byte[] buffer = new byte[fileSize]; //创建一个文件 System.IO.FileInfo file = new System.IO.FileInfo(filePath); //创建一个文件流 using (FileStream fs = file.Open(FileMode.Open)) { //将文件流读入缓冲区 fs.Read(buffer, 0, fileSize); return(buffer); } }
public static void WriteBytesToFile(string path, byte[] bytes, int length) { string directory = GetDirectoryName(path); if (!IsDirectoryExist(directory)) { CreateDirectory(directory); } System.IO.FileInfo fileInfo = new System.IO.FileInfo(path); using (Stream sw = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite)) { if (bytes != null && length > 0) { sw.Write(bytes, 0, length); } } }
public static bool Lock() { var lockPath = LockPath; try { var file = new System.IO.FileInfo(lockPath); var stream = file.Open(FileMode.CreateNew, FileAccess.Write); stream.Write(new byte[0], 0, 0); stream.Flush(); stream.Close(); return(true); } catch { return(false); } }
private void jp_LEVEL_6_log(string inputString)//Level 6 writes data { if (!Directory.Exists(jp_LEVEL_6_folderPath)) { Directory.CreateDirectory(jp_LEVEL_6_folderPath); } try { lock (jpLocker_LEVEL_6) { if (!fileInfo_6.Exists) { jpFileStream_LEVEL_6 = fileInfo_6.Create(); jpWriter_LEVEL_6 = new StreamWriter(jpFileStream_LEVEL_6); } else { jpFileStream_LEVEL_6 = fileInfo_6.Open(FileMode.Append, FileAccess.Write); jpWriter_LEVEL_6 = new StreamWriter(jpFileStream_LEVEL_6); } jpWriter_LEVEL_6.WriteLine("\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\r\n" + "--- LEVEL_6 ---" + inputString); jpWriter_LEVEL_6.Close(); jpWriter_LEVEL_6.Dispose(); jpFileStream_LEVEL_6.Close(); jpFileStream_LEVEL_6.Dispose(); } } catch (Exception e) { Console.WriteLine("ATSLog.writeLogByPath exception for logging LEVEL_6 " + inputString + " at path: " + jp_LEVEL_6_fileName + "->" + e.Message); jpWriter_LEVEL_6.WriteLine("ATSLog.writeLogByPath exception for logging LEVEL_6 " + inputString + " at path: " + jp_LEVEL_6_fileName + "->" + e.Message); } finally { if (jpWriter != null) { } } }
/// <summary> /// Initializes the framework using a <em>System.IO.FileInfo</em> object. /// This object must point to an XML file containing a <em>baseconfig4net</em> /// node. /// </summary> /// <param name="configFileInfo"> /// A <em>System.IO.FileInfo</em> reference. /// </param> public static void Initialize(System.IO.FileInfo configFileInfo) { //FileInfo file = new FileInfo( // Make sure that the system is not initialized again if already done. if (ROOT_PATH == null) { if (configFileInfo == null) { throw new System.ArgumentNullException("configFileInfo", "The parameter [configFileInfo] cannot be null. Unable to initialize the XML Configuration Framework. This can happen when a valid FileInfo reference is not passed to this function. Make sure to pass a valid FileInfo object as the parameter [configFileInfo] to this method."); } // Check to make sure that the file pointed to by 'configFileInfo' // exists. if (File.Exists(configFileInfo.FullName)) { Initialize(configFileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read)); } } }
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(); } } }