static int Main() { byte [] buf = new byte [1]; AsyncCallback ac = new AsyncCallback (async_callback); IAsyncResult ar; int sum0 = 0; FileStream s = new FileStream ("async_read.cs", FileMode.Open); s.Position = 0; sum0 = 0; while (s.Read (buf, 0, 1) == 1) sum0 += buf [0]; s.Position = 0; do { ar = s.BeginRead (buf, 0, 1, ac, buf); } while (s.EndRead (ar) == 1); sum -= buf [0]; Thread.Sleep (100); s.Close (); Console.WriteLine ("CSUM: " + sum + " " + sum0); if (sum != sum0) return 1; return 0; }
public void AppendResultsToFile(String Name, double TotalTime) { FileStream file; file = new FileStream(Name, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(file); sw.Write("***************************************\n"); sw.Write("Total | No Subs| %Total |%No Subs| Name\n"); foreach (CNamedTimer NamedTimer in m_NamedTimerArray) { if (NamedTimer.GetTotalSeconds() > 0) { String OutString; OutString = String.Format("{0:0.0000}", NamedTimer.GetTotalSeconds()) + " | " + String.Format("{0:0.0000}", NamedTimer.GetTotalSecondsExcludingSubroutines()) + " | " + String.Format("{0:00.00}", System.Math.Min(99.99, NamedTimer.GetTotalSeconds() / TotalTime * 100)) + "%" + " | " + String.Format("{0:00.00}", NamedTimer.GetTotalSecondsExcludingSubroutines() / TotalTime * 100) + "%" + " | " + NamedTimer.m_Name; OutString += " (" + NamedTimer.m_Counter.ToString() + ")\n"; sw.Write(OutString); } } sw.Write("\n\n"); sw.Close(); file.Close(); }
static void Main(string[] args) { Settings.LoadOrInitialize(); InitializePreset(); var watcher = new FileSystemWatcher { Path = Settings.ChatLogFolder, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess, Filter = _currentPreset.Channel + "_*.txt" }; try { watcher.Changed += OnChanged; watcher.Created += OnCreated; watcher.EnableRaisingEvents = true; WaitForUserInput(); } finally { _intelStreamReader?.Close(); _intelFileStream?.Close(); } }
public static void JoinFile(string inputFile, string outputFile, KsSplitJoinHandler handler) { long rwIncrament=500000;//updateInterval=400000, updateIndex=0; FileInfo fInfo=new FileInfo(inputFile); long iLen=fInfo.Length; FileStream ifs=new FileStream(inputFile, FileMode.Open); BinaryReader reader=new BinaryReader(ifs); //bool cont; FileInfo fi=new FileInfo(outputFile); FileMode fm=FileMode.Append; if(!fi.Exists) fm=FileMode.CreateNew; FileStream ofs=new FileStream(outputFile, fm); BinaryWriter writer=new BinaryWriter(ofs); long i=0, cnt; while(i<iLen) { cnt=rwIncrament; if((i+cnt)>=iLen) cnt=iLen-i; //byte val[cnt]; writer.Write(reader.ReadBytes((int)cnt)); i+=cnt; if(!handler.OnUpdate(inputFile, outputFile, i, iLen)) { ifs.Close(); reader.Close(); ofs.Close(); writer.Close(); handler.OnCanceled(inputFile, outputFile, i, iLen); return; } } ifs.Close(); reader.Close(); ofs.Close(); writer.Close(); handler.OnFinished(inputFile, outputFile, i, iLen); }
public void saveCurrentName(){ FileStream stream = null; try{ XmlSerializer serializer = new XmlSerializer(typeof(ScreenName)); stream = new FileStream(screenNameFileLocation, FileMode.OpenOrCreate); serializer.Serialize(stream, screenName); stream.Close(); } catch(Exception ex){ if(stream != null) stream.Close(); //throw ex; } }
public void saveCurrentOptions(){ FileStream stream = null; try{ XmlSerializer serializer = new XmlSerializer(typeof(OptionsInfo)); stream = new FileStream(optionsFileLocation, FileMode.OpenOrCreate); serializer.Serialize(stream, newOptions); // new options to disk here stream.Close(); } catch(Exception ex){ Debug.LogError(ex.ToString()); if(stream != null) stream.Close(); } currentOptions = newOptions; }
/// <summary> /// Loads the currentOptions from disk. /// </summary> public void loadCurrentOptions(){ FileStream stream = null; try{ XmlSerializer serializer = new XmlSerializer(typeof(OptionsInfo)); stream = new FileStream(optionsFileLocation, FileMode.Open); OptionsInfo container = (OptionsInfo)serializer.Deserialize(stream); currentOptions = container; stream.Close(); //}catch(Exception ex){ } catch{ if(stream != null) stream.Close(); //Debug.LogError(ex.ToString()); } }
public static GOBFile Open(string path) { //Debug.Log("GOBFile.Open(" + path + ")"); FileStream fs = null; try { fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } catch {} if (fs == null) { Debug.LogError("OpenRead(\"" + path + "\") failed."); return null; } BinaryReader br = new BinaryReader(fs); try { byte[] id = new byte[4]; if (br.Read(id, 0, 4) != 4) { Debug.LogError("Failed to read GOB header in file " + path + "."); fs.Close(); return null; } if ((id[0] != 71) || (id[1] != 79) || (id[2] != 66) || (id[3] != 0xA)) { fs.Close(); Debug.LogError("\"" + path + "\" is not a GOB file."); return null; } int dirOfs = br.ReadInt32(); br.BaseStream.Position = (long)dirOfs; int numFiles = br.ReadInt32(); GOBFile gob = new GOBFile(); byte[] name = new byte[13]; for (int i = 0; i < numFiles; ++i) { File file = File.Read(br, name); gob._dir.Add(file.Name, file); // Debug.Log (file.Name); } gob._file = br; return gob; } catch { using (br) {} } return null; }
// </ThrowException> // <TestFinally> static void TestFinally() { FileStream?file = null; //Change the path to something that works on your machine. FileInfo fileInfo = new System.IO.FileInfo("./file.txt"); try { file = fileInfo.OpenWrite(); file.WriteByte(0xF); } finally { // Closing the file allows you to reopen it immediately - otherwise IOException is thrown. file?.Close(); } try { file = fileInfo.OpenWrite(); Console.WriteLine("OpenWrite() succeeded"); } catch (IOException) { Console.WriteLine("OpenWrite() failed"); } }
private void Read(string filename) { XmlSerializer ser=new XmlSerializer(typeof(DataSet)); FileStream fs=new FileStream(filename, FileMode.Open); DataSet ds; ds=(DataSet)ser.Deserialize(fs); fs.Close(); Console.WriteLine("DataSet name: "+ds.DataSetName); Console.WriteLine("DataSet locale: "+ds.Locale.Name); foreach(DataTable t in ds.Tables) { Console.WriteLine("Table name: "+t.TableName); Console.WriteLine("Table locale: "+t.Locale.Name); foreach(DataColumn c in t.Columns) { Console.WriteLine("Column name: "+c.ColumnName); Console.WriteLine("Null allowed? "+c.AllowDBNull); } foreach(DataRow r in t.Rows) { Console.WriteLine("Row: "+(string)r[0]); } } }
public void ImportProteinSettings() { try { ////read serializer = new XmlSerializer(typeof(CutParametersContainer)); stream = new FileStream(path, FileMode.Open); CutParametersContainer importParams = serializer.Deserialize(stream) as CutParametersContainer; stream.Close(); for (int i = 0; i < importParams.CutObjectProps.Count && i < SceneManager.Get.CutObjects.Count; i++) { SceneManager.Get.CutObjects[i].IngredientCutParameters = importParams.CutObjectProps[i].ProteinTypeParameters; SceneManager.Get.CutObjects[i].Inverse = importParams.CutObjectProps[i].Inverse; SceneManager.Get.CutObjects[i].CutType = (CutType) importParams.CutObjectProps[i].CutType; //restore transform info SceneManager.Get.CutObjects[i].transform.rotation = importParams.CutObjectProps[i].rotation; SceneManager.Get.CutObjects[i].transform.position = importParams.CutObjectProps[i].position; SceneManager.Get.CutObjects[i].transform.localScale = importParams.CutObjectProps[i].scale; } } catch(Exception e) { Debug.Log("import failed: " + e.ToString()); return; } Debug.Log("imported cutobject settings from " + path); }
public static void Main() { const char DELIM = ','; const string FILENAME = "EmployeeData.txt"; Employee emp = new Employee(); FileStream inFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(inFile); string recordIn; string[] fields; Console.WriteLine("\n{0,-5}{1,-12}{2,8}\n", "Num", "Name", "Salary"); recordIn = reader.ReadLine(); while(recordIn != null) { fields = recordIn.Split(DELIM); emp.EmpNum = Convert.ToInt32(fields[0]); emp.Name = fields[1]; emp.Salary = Convert.ToDouble(fields[2]); Console.WriteLine("{0,-5}{1,-12}{2,8}", emp.EmpNum, emp.Name, emp.Salary.ToString("C")); recordIn = reader.ReadLine(); } reader.Close(); inFile.Close(); }
//------------------------------------------------------------------------------------------------------------ private void OnGUI() { m_MeshFilter = (MeshFilter)EditorGUILayout.ObjectField("MeshFilter", m_MeshFilter, typeof(MeshFilter), true); if (m_MeshFilter != null) { if (GUILayout.Button("Export OBJ")) { var lOutputPath = EditorUtility.SaveFilePanel("Save Mesh as OBJ", "", m_MeshFilter.name + ".obj", "obj"); if (File.Exists(lOutputPath)) { File.Delete(lOutputPath); } var lStream = new FileStream(lOutputPath, FileMode.Create); var lOBJData = m_MeshFilter.sharedMesh.EncodeOBJ(); OBJLoader.ExportOBJ(lOBJData, lStream); lStream.Close(); } } else { GUILayout.Label("Please provide a MeshFilter"); } }
public void UploadFile(RemoteFileInfo request) { try { FileGonnaGo objFileUpload = new FileGonnaGo(); if (objFileUpload.impersonateValidUser()) { FileStream targetStream = null; Stream sourceStream = request.FileByteStream; string uploadFolder = objFileServerImpersonation.FileServerPath(); string filePath = Path.Combine(uploadFolder, request.FileName); using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 21474833; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); sourceStream.Close(); } objFileUpload.undoImpersonation(); } } catch (Exception ex) { WCFFILESERVER.FileService.LogException(string.Empty, ex); throw; } }
public void Write(string logfilename, string log, LogType lt) { #if UNITY_IPHONE || UNITY_ANDROID return; #endif string filePathName = WriteFile(logfilename); FileStream fs = new FileStream(filePathName, FileMode.Append); StreamWriter sw = new StreamWriter(fs); //开始写入 sw.WriteLine(""); // string str = "["; str += System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");//默认当天时间。 str += "]"; str += "\t"; str += lt.ToString(); str += "\t"; str += log; sw.Write(str); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); }
static void Assemble(List<string> files, string destinationDirectory) { string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[3]; var fsSource = new FileStream(fileOutputPath, FileMode.Create); fsSource.Close(); using (fsSource = new FileStream(fileOutputPath, FileMode.Append)) { // reading the file paths of the parts from the files list foreach (var filePart in files) { using (var partSource = new FileStream(filePart, FileMode.Open)) { using (var compressionStream = new GZipStream(partSource,CompressionMode.Decompress,false)) { // copy the bytes from part to new assembled file Byte[] bytePart = new byte[4096]; while (true) { int readBytes = compressionStream.Read(bytePart, 0, bytePart.Length); if (readBytes == 0) { break; } fsSource.Write(bytePart, 0, readBytes); } } } } } }
public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string asset in importedAssets) { if (asset.EndsWith(".resx")) { string filePath = asset.Substring(0, asset.Length - Path.GetFileName(asset).Length) + "Generated Assets/"; string newFileName = filePath + Path.GetFileNameWithoutExtension(asset) + ".txt"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //Delete the file if it already exists if(File.Exists(newFileName)) { File.Delete(newFileName); } StreamReader reader = new StreamReader(asset); string fileData = reader.ReadToEnd(); reader.Close(); FileStream resourceFile = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter writer = new StreamWriter(resourceFile); writer.Write(fileData); writer.Close(); resourceFile.Close(); AssetDatabase.Refresh(ImportAssetOptions.Default); } } }
public void Deserialize(string path) { XmlSerializer serializer = new XmlSerializer(typeof(Edge)); FileStream stream = new FileStream(path, FileMode.Open); copy(serializer.Deserialize(stream) as Edge); stream.Close(); }
private void getFile() { TcpClient client = list.AcceptTcpClient(); StreamReader sr = new StreamReader(client.GetStream()); string rd = sr.ReadLine(); string v = rd.Substring(rd.LastIndexOf('.') + 1); Debug.Log("reading file. Length: " + v + " bytes."); TcpClient client2 = list2.AcceptTcpClient(); Debug.Log("reading from rnetworkStream"); NetworkStream rnetworkStream = client2.GetStream(); FileStream fileStream = new FileStream(receiveFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); long filezie = int.Parse(v); int byteSize = 0; byte[] downBuffer = new byte[2048]; while ((byteSize = rnetworkStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { fileStream.Write(downBuffer, 0, byteSize); } fileStream.Close(); rnetworkStream.Close(); client.Close (); client2.Close (); Debug.Log("Finish geting file"); }
public static conf load(string filename) { // Declare an object variable of the type to be deserialized. conf po; try { // Create an instance of the XmlSerializer class; // specify the type of object to be deserialized. XmlSerializer serializer = new XmlSerializer(typeof(conf)); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); /* Use the Deserialize method to restore the object's state with data from the XML document. */ po = (conf)serializer.Deserialize(fs); fs.Close(); return po; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
public void Serialize(string path) { XmlSerializer serializer = new XmlSerializer(typeof(Edge)); FileStream stream = new FileStream(path, FileMode.Append); serializer.Serialize(stream, this); stream.Close(); }
public static void SaveToFile(Level data, string fileName) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(string.Format("{0}.level", fileName), FileMode.Create, FileAccess.Write, FileShare.Write); formatter.Serialize(stream, data); stream.Close(); }
public static string LoadName(string path) { // The idea is to read only the number of bytes we need to determine the name of the timeline // We're going to exploit our knowledge of the way the unpacker works to do this - kinda hacky, but eh // Maybe one of these days I'll change the unpacker over to work with streams instead of byte arrays // Probably not // ...definitely not FileStream fs = new FileStream(path, FileMode.Open); // Skip over the version fs.Position = 4; // Read the length of the string byte[] strLengthBytes = new byte[4]; fs.Read(strLengthBytes, 0, 4); int strLength = BitConverter.ToInt32(strLengthBytes, 0); // Read the actual string data byte[] strBytes = new byte[strLength]; fs.Read(strBytes, 0, strLength); // Tidy up the stream fs.Close(); // Unpack and return the string char[] cArray = System.Text.Encoding.Unicode.GetChars(strBytes, 0, strBytes.Length); return new string(cArray); }
public static bool Load(Chunk chunk) { string saveFile = SaveLocation(chunk.world.worldName); saveFile += FileName(chunk.pos); if (!File.Exists(saveFile)) return false; try { IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Open); Save save = (Save)formatter.Deserialize(stream); //Once the blocks in the save are added they're marked as unmodified so //as not to trigger a new save on unload unless new blocks are added. for (int i =0; i< save.blocks.Length; i++) { Block placeBlock = save.blocks[i]; placeBlock.modified = false; chunk.SetBlock(save.positions[i], placeBlock, false); } stream.Close(); } catch (Exception ex) { Debug.LogError(ex); } return true; }
/// <summary> /// Creates a new window with the given window ID and the current window UI /// </summary> public void CreateNewWindow(int windowID) { if (!Directory.Exists(Application.persistentDataPath + "/Windows")) { Directory.CreateDirectory(Application.persistentDataPath + "/Windows/"); } string path = Application.persistentDataPath; if (windowID == -1) path += "/Windows/BaseWindow.txt"; else path += "/Windows/Window" + windowID.ToString() + ".txt"; try { myData = new WindowData(); myData.windowID = windowID; using (FileStream fs = new FileStream(path, FileMode.Create)) { XmlSerializer xmls = new XmlSerializer(typeof(WindowData)); xmls.Serialize(fs, myData); fs.Close(); } Debug.Log ("Succesfully wrote UIWindow to " + path); } catch (InvalidOperationException e) { Debug.LogError ("Failed to write UIWindow to " + path + "- Error: " + e.Message); } }
public void ExportProteinSettings() { try { CutParametersContainer exportParams = new CutParametersContainer(); foreach (CutObject cuto in SceneManager.Get.CutObjects) { CutObjectProperties props = new CutObjectProperties(); props.ProteinTypeParameters = cuto.IngredientCutParameters; props.Inverse = cuto.Inverse; props.CutType = (int)cuto.CutType; props.rotation = cuto.transform.rotation; props.position = cuto.transform.position; props.scale = cuto.transform.localScale; exportParams.CutObjectProps.Add(props); } ////write serializer = new XmlSerializer(typeof(CutParametersContainer)); stream = new FileStream(path, FileMode.Create); serializer.Serialize(stream, exportParams); stream.Close(); } catch(Exception e) { Debug.Log("export failed: " + e.ToString()); return; } Debug.Log("exported cutobject settings to " + path); }
private static void Assemble(List<string> files, string destinationDirectory) { string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[2]; var fsSource = new FileStream(fileOutputPath, FileMode.Create); fsSource.Close(); using (fsSource = new FileStream(fileOutputPath, FileMode.Append)) { foreach (var filePart in files) { using (var partSource = new FileStream(filePart, FileMode.Open)) { Byte[] bytePart = new byte[4096]; while (true) { int readBytes = partSource.Read(bytePart, 0, bytePart.Length); if (readBytes == 0) { break; } fsSource.Write(bytePart, 0, readBytes); } } } } }
private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV) { FileStream fs = new FileStream(inName, FileMode.Open, FileAccess.Read); // Create an instance of the Rijndael cipher SymmetricAlgorithm aes = Rijndael.Create(); // set the key to be the derivedKey computed above aes.Key = desKey; // set the IV to be all zeros aes.IV = desIV; // arrays are zero-initialized // now wrap an encryption transform around the filestream CryptoStream stream1 = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Read); // The result of reading from stream1 is ciphertext, but we want it // base64-encoded, so wrap another transform around it CryptoStream stream2 = new CryptoStream(stream1, new ToBase64Transform(), CryptoStreamMode.Read); FileStream fsout = new FileStream(outName, FileMode.OpenOrCreate); byte[] buffer = new byte[1024]; int bytesRead; do { bytesRead = stream2.Read(buffer,0,1024); fsout.Write(buffer,0,bytesRead); } while (bytesRead > 0); fsout.Flush(); fsout.Close(); }
private static void Assemble(List<string> files, string destinationDirectory) { // creating the file path for the reconstructed file string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[2]; var fsSource = new FileStream(fileOutputPath, FileMode.Create); fsSource.Close(); using (fsSource = new FileStream(fileOutputPath, FileMode.Append)) { // reading the file paths of the parts from the files list foreach (var filePart in files) { using (var partSource = new FileStream(filePart, FileMode.Open)) { // Create a byte array of the content of the current file Byte[] bytePart = new byte[4096]; while (true) { int readBytes = partSource.Read(bytePart, 0, bytePart.Length); if (readBytes == 0) { break; } // Write the bytes to the reconstructed file fsSource.Write(bytePart, 0, readBytes); } } } } }
void Serialize(string filename){ // normalizes the data to the {0.0-1.0f} interval and saves as xml Waveform w = new Waveform(); w.name = filename; w.cycles=1; w.signal = signal; w.mode=filename; w.normalRate = normal; w.samples = dataPoints.Count; float scale = dataMax-dataMin; if ( scale == 0.0f ) scale = 1.0f; w.data = new float[dataPoints.Count]; for (int i=0;i< dataPoints.Count;i++){ w.data[i]= (dataPoints[i].point-dataMin)/scale; } XmlSerializer serializer = new XmlSerializer(typeof(Waveform)); FileStream stream = new FileStream(filename + ".xml", FileMode.Create); serializer.Serialize(stream, w); stream.Close(); }
public void WriteDust(string path) { XmlSerializer serializer = new XmlSerializer(typeof(ScriptDustItemsContainer)); FileStream stream = new FileStream(path, FileMode.Create); serializer.Serialize(stream, this); stream.Close(); }
static IEnumerator Compute(string path, OnFinish on_finish) { FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); byte[] buffer = new byte[kBlockSize]; MD5 md5 = MD5.Create(); int length, read_bytes; while (stream.Position < stream.Length) { length = (stream.Position + kBlockSize > stream.Length) ? (int)(stream.Length - stream.Position) : kBlockSize; read_bytes = stream.Read(buffer, 0, length); if (stream.Position < stream.Length) { md5.TransformBlock(buffer, 0, read_bytes, buffer, 0); } else { md5.TransformFinalBlock(buffer, 0, read_bytes); stream.Close(); break; } yield return new WaitForEndOfFrame(); } string md5hash = ""; foreach (byte n in md5.Hash) md5hash += n.ToString("x2"); Fun.DebugUtils.Log(String.Format("MD5 >> {0} > {1}", stream.Name, md5hash)); if (on_finish != null) on_finish(md5hash); }
public void UnlockDataFolder() { _fileStream?.Close(); try { File.Delete(_lockFileName); } catch { } }
protected async Task StopGuardAsync() { _logStreamWriter?.Close(); _logFileStream?.Close(); try { if (Instance is { HasExited : false }) { Instance.Kill(); await Instance.WaitForExitAsync(); } }
public static void Init(SentryUnityOptions options) { SentryOptionsUtility.TryAttachLogger(options); if (options.ShouldInitializeSdk()) { // On Standalone, we disable cache dir in case multiple app instances run over the same path. // Note: we cannot use a named Mutex, because Unit doesn't support it. Instead, we create a file with `FileShare.None`. // https://forum.unity.com/threads/unsupported-internal-call-for-il2cpp-mutex-createmutex_internal-named-mutexes-are-not-supported.387334/ if (ApplicationAdapter.Instance.Platform is RuntimePlatform.WindowsPlayer && options.CacheDirectoryPath is not null) { try { _lockFile = new FileStream(Path.Combine(options.CacheDirectoryPath, "sentry-unity.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch (Exception ex) { options.DiagnosticLogger?.LogWarning("An exception was thrown while trying to " + "acquire a lockfile on the config directory: .NET event cache will be disabled.", ex); options.CacheDirectoryPath = null; options.AutoSessionTracking = false; } } var sentryDotNet = SentrySdk.Init(options); ApplicationAdapter.Instance.Quitting += () => { options.DiagnosticLogger?.LogDebug("Closing the sentry-dotnet SDK"); try { sentryDotNet.Dispose(); } finally { try { // We don't really need to close, Windows would release the lock anyway, but let's be nice. _lockFile?.Close(); } catch (Exception ex) { options.DiagnosticLogger?.Log(SentryLevel.Warning, "Exception while releasing the lockfile on the config directory.", ex); } } }; } }
static void CloseOptionally() { //<CleanupIfNotNull> FileStream?file = null; FileInfo fileinfo = new System.IO.FileInfo("./file.txt"); try { file = fileinfo.OpenWrite(); file.WriteByte(0xF); } finally { // Check for null because OpenWrite might have failed. file?.Close(); } //</CleanupIfNotNull> }
private static bool IsFileLocked(string filePath) { FileStream?stream = null; try { stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (IOException) { return(true); } finally { stream?.Close(); } return(false); }
// </NoCleanup> // <WithCleanup> static void CodeWithCleanup() { FileStream?file = null; FileInfo? fileInfo = null; try { fileInfo = new FileInfo("./file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } finally { file?.Close(); } }
public static ClrtDisplayableType[] DeserializeArray(string path, out string error) { error = null; Stream stream = null; try { IFormatter formatter = new BinaryFormatter(); stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); ClrtDisplayableType[] ary = (ClrtDisplayableType[])formatter.Deserialize(stream); return(ary); } catch (Exception ex) { error = Utils.GetExceptionErrorString(ex); return(null); } finally { stream?.Close(); } }
public async Task <string> Save(Stream content, string name) { var storePath = Path.Combine(BasePath, StoragePath, name); FileStream fileStream = default; try { fileStream = new FileStream(storePath, FileMode.Create); await content.CopyToAsync(fileStream); fileStream.Close(); } catch (Exception) { return(null); } finally { fileStream?.Close(); } return(new Uri(Path.Combine(AccessURI.AbsoluteUri, StoragePath, name)).AbsoluteUri); }
private void Dispose(bool disposing) { if (!_disposed) { if (disposing) { Lock(); try { _storageStream?.Close(); _pagemap.Dispose(); _recoveryFile?.Dispose(); } finally { Unlock(); } } _disposed = true; } }
public static string BinaryFileSerialize(Object obj, string filePath) { FileStream fileStream = null; string errorMsg = null; try { fileStream = new FileStream(filePath, FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(fileStream, obj); } catch (Exception e) { errorMsg = e.Message; } finally { fileStream?.Close(); } return(errorMsg); }
public bool LoadLicenceFromFile(string filename) { FileStream fs = null; try { if (!File.Exists(filename)) { return(false); } fs = File.OpenRead(filename); if (fs.Length > MAX_FILE_SIZE) { throw new Exception("Invalid length of licence file"); } TextReader tr = new StreamReader(fs); string licenceBase64 = tr.ReadToEnd(); fs.Close(); _licenceData = ObjectSerializer.DeserializeLicenceDataFromString(licenceBase64); _serviceState.Valid = false; _serviceState.Validated = false; return(_licenceData != null); } catch (Exception ex) { Log.Error(ex, "LoadLicenceFromFile"); } finally { fs?.Close(); } return(false); }
/// <summary> /// At end of using frees opened locking stream (if opened) and if it was aquired before - deletes lock file /// </summary> public void Dispose() { str?.Close(); if (!IsAquired) { return; } if (!File.Exists(PidFilePath)) { return; } try { File.Delete(PidFilePath); } catch { Thread.Sleep(WAIT_TIMEOUT_STEP); if (File.Exists(PidFilePath)) { File.Delete(PidFilePath); } } }
IEnumerator Start() { Loaded = false; status.text = "Downloading most recent mod database..."; WWW www = new WWW(ModLinksURL); while (!www.isDone) { yield return(null); } FileStream fstream = null; try { fstream = new FileStream(ModLinksPath, FileMode.Create); BinaryWriter writer = new BinaryWriter(fstream); writer.Write(www.bytes); writer.Close(); } catch (System.Exception e) { System.Windows.Forms.MessageBox.Show("Error downloading modlinks: " + e.Message); } finally { } fstream?.Close(); www?.Dispose(); yield return(null); ReadModLinksFromFile(ModLinksPath, out modLinks); Loaded = true; }
public static void Select(object sender, string path) { RichTextBox TxtBox = sender as RichTextBox; TxtBox.Document.Blocks.Clear(); if (File.Exists(path)) { File1 = new FileStream(path, FileMode.Open); } else { return; } TextRange range = new TextRange(TxtBox.Document.ContentStart, TxtBox.Document.ContentEnd); try { // Чтение файла формата Rtf range.Load(File1, System.Windows.DataFormats.Text); } catch (Exception) { File1.Close(); FileStream fileStream = new FileStream(path, FileMode.Create); range = new TextRange(TxtBox.Document.ContentStart, TxtBox.Document.ContentEnd); range.Save(fileStream, System.Windows.DataFormats.Rtf); //Закрываем поток чтения файла fileStream.Close(); range.Load(File1, System.Windows.DataFormats.Rtf); } finally { File1?.Close(); } }
/// <summary> /// Загрузка из файла /// </summary> public static JObject Load(string fileName) { FileStream fs = null; StreamReader sr = null; try { fs = new FileStream(fileName, FileMode.Open); sr = new StreamReader(fs); return(JObject.Parse(sr.ReadToEnd())); } catch (Exception ex) { Console.WriteLine(ex); return(null); } finally { sr?.Close(); fs?.Close(); } }
public static T Load <T>(string fileName) { FileStream fs = null; StreamReader sr = null; try { fs = new FileStream(fileName, FileMode.Open); sr = new StreamReader(fs); return(JsonConvert.DeserializeObject <T>(sr.ReadToEnd())); } catch (Exception ex) { Console.WriteLine(ex); return(default(T)); } finally { sr?.Close(); fs?.Close(); } }
/// <summary> /// 文件转化为byte[] /// </summary> /// <param name="fileName">文件路径</param> /// <returns></returns> public static byte[] ReadFile(string fileName) { FileStream pFileStream = null; try { pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); var r = new BinaryReader(pFileStream); //将文件指针设置到文件开 r.BaseStream.Seek(0, SeekOrigin.Begin); var pReadByte = r.ReadBytes((int)r.BaseStream.Length); return(pReadByte); } catch (Exception ex) { throw new Exception(ex.Message); } finally { pFileStream?.Close(); } }
public static void Log(string message) { lock (FileFolderHelper.LogFilepath) { StreamWriter writer = null; FileStream file = null; try { FileFolderHelper.CheckAndCreateFile(FileFolderHelper.LogFilepath); file = new FileStream(FileFolderHelper.LogFilepath, FileMode.Append); writer = new StreamWriter(file); writer.WriteLine(DateTime.Now.ToString("HH:mm:ss.ms") + " " + message); } finally { writer?.Close(); file?.Close(); writer = null; file = null; } } }
public static bool SerializeArray(string path, ClrtDisplayableType[] ary, out string error) { error = null; Stream stream = null; try { IFormatter formatter = new BinaryFormatter(); stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); formatter.Serialize(stream, ary); return(true); } catch (Exception ex) { error = Utils.GetExceptionErrorString(ex); return(false); } finally { stream?.Close(); } }
// Validate that we can write to the file. This will enforce the ACL's // on the file. Since we do our moving of files to replace, this is // nice to ensure we are not by-passing some security permission // that someone set (although that could bypass this via move themselves) // // Note: 1) This is really just a nice to have, since with directory permissions // they could do the same thing we are doing // // 2) We are depending on the current behavior that if the file is locked // and we can not open it, that we will get an UnauthorizedAccessException // and not the IOException. private void ValidateWriteAccess(string filename) { FileStream fs = null; try { // Try to open file for write access fs = new FileStream(filename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); } catch (IOException) { // Someone else was using the file. Since we did not get // the unauthorizedAccessException we have access to the file } finally { fs?.Close(); } }
public void Upload(string remoteFile, string localFile) { var localFileStream = null as FileStream; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ localFileStream = new FileStream(localFile, FileMode.Open); /* Buffer for the Downloaded Data */ var byteBuffer = new byte[bufferSize]; var bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); } } finally { /* Resource Cleanup */ localFileStream?.Close(); ftpStream?.Close(); ftpRequest = null; } }
private bool IsFileinUse(FileInfo file) { 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 { stream?.Close(); } return(false); }
public RegistrationDataModel ReadRegistrationDataFromFile(string filename) { FileStream fs = null; try { fs = File.OpenRead(filename); TextReader tr = new StreamReader(fs); string requestInBase64 = tr.ReadToEnd(); fs.Close(); return(ObjectSerializer.DeserializeRegistrationDataFromString(requestInBase64)); } catch (Exception ex) { Log.Error(ex, $"Failed to open {filename}"); } finally { fs?.Close(); } return(null); }
public static Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite) { var pathname = Path.GetFullPath(filename); if (!overwrite && File.Exists(filename)) { throw new InvalidOperationException($@"File {pathname} already exists."); } FileStream fileStream = null; try { fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None); return(content.CopyToAsync(fileStream).ContinueWith(copyTask => { fileStream.Close(); })); } catch { fileStream?.Close(); throw; } }
public void Work(string source, string destination) { FileStream writeStream = null; FileStream readStream = null; try { FileInfo fileInfo = new FileInfo(source); long fileSize = fileInfo.Length; long total = 0; int bytesRead = -1; int buffLength = 1024 * 1024; byte[] buff = new byte[buffLength]; int invoked = 0; writeStream = new FileStream(destination, FileMode.CreateNew, FileAccess.Write); readStream = new FileStream(source, FileMode.Open, FileAccess.Read); do { bytesRead = readStream.Read(buff, 0, buffLength); writeStream.Write(buff, 0, bytesRead); total += bytesRead; ProgressInfo pi = new ProgressInfo(total, fileSize, fileInfo.Name); if (Progress && ((int)pi.Progress) / 10 > invoked) { OnProgress(pi, false, ConsoleColor.Blue); //ProgressEvent?.Invoke(pi, false); invoked++; } } while (bytesRead > 0); writeStream.Flush(); } finally { writeStream?.Close(); readStream?.Close(); } Console.WriteLine($"Finished Copy: {Thread.CurrentThread.ManagedThreadId}"); }
/// <summary> /// 根据文件创建工作簿对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <returns></returns> private static IWorkbook CreateWorkbook <T>(string filePath) where T : new() { IWorkbook wk; var allowExtensions = new List <string>() { ".xlsx", ".xls" }; var extension = Path.GetExtension(filePath); if (!allowExtensions.Contains(extension, StringComparer.CurrentCultureIgnoreCase)) { throw new ArgumentException("只支持xlsx,xls 类型文件"); } FileStream fs = null; try { fs = File.OpenRead(filePath); if (extension != null && extension.Equals(".xls")) { wk = new HSSFWorkbook(fs); } else { wk = new XSSFWorkbook(fs); } } catch (Exception ex) { throw new Exception(ex.Message); } finally { fs?.Close(); } return(wk); }
public static byte[] ReadFile(string fileName) { FileStream pFileStream = null; byte[] pReadByte = new byte[0]; try { pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(pFileStream); r.BaseStream.Seek(0L, SeekOrigin.Begin); pReadByte = r.ReadBytes((int)r.BaseStream.Length); return(pReadByte); } catch { return(pReadByte); } finally { pFileStream?.Close(); } }
/// <summary> /// Function verifies DjVu file header and expects minimum length of 16 bytes. /// In sixteen bytes first eight form AT&TFORM ASCII text, 4 following ones /// contain length of DjVu file data (counted from first byte after file length field /// at position 12) and first chunk name being second part of form name (DJVM, DJVU, DJVI). /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool IsDjvuDocument(string filePath) { if (!string.IsNullOrWhiteSpace(filePath)) { FileStream stream = null; bool result = false; if (File.Exists(filePath)) { try { stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); result = IsDjvuDocument(stream); } catch (Exception error) { throw new DjvuAggregateException("Error while trying to verify DjVu file.", error); } finally { stream?.Close(); } return(result); } else { throw new DjvuFileNotFoundException("File was not found.", filePath); } } if (filePath == null) { throw new DjvuArgumentNullException(nameof(filePath)); } else { throw new DjvuArgumentException($"Invalid file path: \"{filePath}\"", nameof(filePath)); } }