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(); }
private static void CheckUpdateCurrentLogStream() { DateTime nowTimestamp = DateTime.Now; nowTimestamp = new DateTime(year: nowTimestamp.Year, month: nowTimestamp.Month, day: nowTimestamp.Day, hour: nowTimestamp.Hour, minute: 0, second: 0); string nowStamp = nowTimestamp.ToString("yyyy-MM-dd HH-mm", CultureInfo.InvariantCulture); if (!nowStamp.Equals(openLogStreamStamp)) { lock (eventLogsWriter) lock (snmpDataWriter) try { eventLogsWriter?.Flush(); eventLogsWriter?.Close(); snmpDataWriter?.Flush(); snmpDataWriter?.Close(); } catch { } finally { openLogStreamStamp = nowStamp; eventLogsWriter = new StreamWriter(path: Path.Combine(EVT_LOGS_DIR, $"{nowStamp}.txt"), append: false); snmpDataWriter = new StreamWriter(path: Path.Combine(SNMP_DATA_DIR, $"{nowStamp}.csv"), append: false); snmpDataWriter.WriteLine($"Time, IPAddress, LreLinkStatusA, LreLinkStatusB, LrePortAdminStateA, LrePortAdminStateB, LreCntTxA, LreCntTxB , LreCntTxC, LreCntRxA, LreCntRxB, LreCntRxC, LreCntErrorsA, LreCntErrorsB, LreCntErrorsC, LreCntOwnRxA, LreCntOwnRxB{Environment.NewLine}"); } } }
/// <summary> /// Initialize stream writer's for push logs into log files. /// </summary> private static void LogInitizaliationStreamWriter() { LogApiStreamWriter?.Close(); LogGeneralStreamWriter?.Close(); LogWalletUpdaterStreamWriter?.Close(); LogSyncStreamWriter?.Close(); LogRemoteNodeSyncStreamWriter?.Close(); LogGeneralStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogGeneral), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogWalletUpdaterStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogWalletUpdater), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogApiStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogApi), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogSyncStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogSync), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogRemoteNodeSyncStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogRemoteNodeSync), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; }
private void SaveScores(string name, int score) { if (_highscores.ContainsKey(name)) { _highscores[name] = score; } else { _highscores.Add(name, score); } StreamWriter writer = null; try { writer = new StreamWriter(HIGHSCOREPATH, false); foreach (KeyValuePair <string, int> entry in _highscores) { writer.WriteLine(entry.Key + "|" + entry.Value); } } catch (Exception e) { Console.WriteLine(e.Message); writer?.Close(); } writer?.Close(); }
public void Save(string path, ItemType itemType) { TextWriter WriteFileStream = new StreamWriter(path); XmlSerializer serializer; switch(itemType) { case ItemType.Armor: serializer = new XmlSerializer(typeof(List<Armor>)); serializer.Serialize(WriteFileStream,ArmorList); WriteFileStream.Close (); break; case ItemType.Weapon: serializer = new XmlSerializer(typeof(List<Weapon>)); serializer.Serialize(WriteFileStream,WeaponList); WriteFileStream.Close (); break; case ItemType.Misc: serializer = new XmlSerializer(typeof(List<Misc>)); serializer.Serialize(WriteFileStream, MiscList); WriteFileStream.Close(); break; case ItemType.Consumable: serializer = new XmlSerializer(typeof(List<Consumable>)); serializer.Serialize(WriteFileStream, ConsumableList); WriteFileStream.Close(); break; case ItemType.Quest: serializer = new XmlSerializer(typeof(List<Quest>)); serializer.Serialize(WriteFileStream, QuestList); WriteFileStream.Close(); break; case ItemType.Enhancer: serializer = new XmlSerializer(typeof(List<Enhancer>)); serializer.Serialize(WriteFileStream, EnhancerList); WriteFileStream.Close(); break; case ItemType.Generator: serializer = new XmlSerializer(typeof(List<Generator>)); serializer.Serialize(WriteFileStream, GeneratorList); WriteFileStream.Close(); break; } }
public static void RVExtension(StringBuilder output, int outputSize, [MarshalAs(UnmanagedType.LPStr)] string input) { byte[] bytes = Encoding.Default.GetBytes(input); input = Encoding.UTF8.GetString(bytes); var colonIndex = input.IndexOf(":"); var operationType = input.Substring(0, colonIndex); var stringToWrite = input.Substring(colonIndex + 1, input.Length - colonIndex - 1); if (operationType.Equals("open")) { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filePath = Path.Combine(assemblyFolder, stringToWrite); outputFile?.Close(); try { outputFile = new StreamWriter(filePath); } catch (System.UnauthorizedAccessException ex) { output.Append("AccessDenied " + ex.Message); return; } catch (DirectoryNotFoundException ex) { output.Append("DirectoryNotFound " + ex.Message); return; } catch (IOException ex) { output.Append("IOException " + ex.Message); return; } catch (System.Exception ex) { output.Append("Exception " + ex.Message); return; } output.Append("true"); return; } else if (operationType.Equals("write")) { outputFile?.WriteLine(stringToWrite); output.Append(outputFile != null ? "true" : "false"); return; } else if (operationType.Equals("close")) { output.Append(outputFile != null ? "true" : "false"); outputFile?.Close(); outputFile = null; return; } output.Append("false"); }
public static void Main(String[] args) { StreamReader sr=null; StreamWriter sw=null; TcpClient client=null; TcpListener server=null; try { //Echo servers listen on port 7 int portNumber = 7; //Echo server first binds to port 7 server = new TcpListener(portNumber); //Server starts listening server.Start(); //Echo server loops forever, listening for clients for(;;) { Console.WriteLine("Waiting for a connection...."); //Accept the pending client connection and return a client //initialized for communication //This method will block until a connection is made client = server.AcceptTcpClient(); Console.WriteLine("Connection accepted."); //Make a user-friendly StreamReader from the stream sr=new StreamReader(client.GetStream()); //Make a user-friendly StreamWriter from the stream sw=new StreamWriter(client.GetStream()); String incoming=sr.ReadLine(); while (incoming!=".") { Console.WriteLine("Message received: "+incoming); sw.WriteLine(incoming); sw.Flush(); Console.WriteLine("Message Sent back: " + incoming); incoming=sr.ReadLine(); } Console.WriteLine("Client sent '.': closing connection."); sr.Close(); sw.Close(); client.Close(); } } catch (Exception e) { Console.WriteLine(e+" "+e.StackTrace); } finally { if (sr!=null) sr.Close();//check if the stream reader is present - if it is, close it if (sw!=null) sw.Close();//check if the stream writer is present - if it is, close it if (client!=null) client.Close(); //Release the port and stop the server server.Stop(); } }
public void Close() { if (isDisposed) { throw new ObjectDisposedException(nameof(ProjectLogger)); } streamWriter?.Flush(); streamWriter?.Close(); streamWriter = null; }
private async void OnDone() { txtBlock_UnMolkingFiles.Text += "___________________________\n"; txtBlock_UnMolkingFiles.Text += "Done!\n"; done = true; await Task.Delay(1300); Helpers.ChangeVisibility(grid_UnMolkingPage); Helpers.ChangeVisibility(grid_UnMolkerPage); errorFile?.Close(); }
private async void OnDone() { txtBlock_MolkingFiles.Text += "___________________________\n"; txtBlock_MolkingFiles.Text += "Done!\n"; done = true; scroll.ScrollToVerticalOffset(-scroll.ActualHeight); await Task.Delay(1300); Helpers.ChangeVisibility(grid_MolkingPage); Helpers.ChangeVisibility(grid_MolkerPage); errorFile?.Close(); }
public static void Main() { try { bool status = true ; string servermessage = "" ; string clientmessage = "" ; TcpListener tcpListener = new TcpListener(8100) ; tcpListener.Start() ; Console.WriteLine("Server Started") ; Socket socketForClient = tcpListener.AcceptSocket() ; Console.WriteLine("Client Connected") ; NetworkStream networkStream = new NetworkStream(socketForClient) ; StreamWriter streamwriter = new StreamWriter(networkStream) ; StreamReader streamreader = new StreamReader(networkStream) ; while(status) { if(socketForClient.Connected) { servermessage = streamreader.ReadLine() ; Console.WriteLine("Client:"+servermessage) ; if((servermessage== "bye" )) { status = false ; streamreader.Close() ; networkStream.Close() ; streamwriter.Close() ; return ; } Console.Write("Server:") ; clientmessage = Console.ReadLine() ; streamwriter.WriteLine(clientmessage) ; streamwriter.Flush() ; } } streamreader.Close() ; networkStream.Close() ; streamwriter.Close() ; socketForClient.Close() ; Console.WriteLine("Exiting") ; } catch(Exception e) { Console.WriteLine(e.ToString()) ; } }
public void StopRecording() { try { recordStream?.Close(); } catch { } isRecording = false; recordStatus = "Idle"; StopReceivingCan(); timer?.Stop(); }
public virtual string CloseConsole(UserGameParam param, string closeCommand = "") { var run = $"^b d"; if (Terminal == null || Writer == StreamWriter.Null) { return(""); } Writer?.WriteLine(run); FoundConsoleEnd = null; Terminal.DataReceived += Terminal_DataReceived; Writer?.Close(); Writer?.Dispose(); Writer = StreamWriter.Null; Terminal?.Close(); Terminal?.Dispose(); return(CollectResiveString); }
public static void UpdateUnityAppController(string path) { const string filePath = "Classes/UnityAppController.mm"; string fullPath = Path.Combine(path, filePath); var reader = new StreamReader(fullPath); string AppControllerSource = reader.ReadToEnd(); reader.Close(); // Add header import AppControllerSource = AddHeaderImportFramework(AppControllerSource); // Add Appota Handler Callback AppControllerSource = AddAppotaHandlerCallback(AppControllerSource); // Add callback register Push Notification AppControllerSource = AddCallbackRegisterPushNotifications(AppControllerSource); // Call Facebook activeApp() inside applicationDidBecomeActive function AppControllerSource = AddFacebookAppEvents(AppControllerSource); // Add callback register Push Notification with Token data AppControllerSource = AddCallbackRegisterPushNotificationWithTokenData(AppControllerSource); if (AppotaSetting.UsingAppFlyer) AppControllerSource = AddAppFlyerConfigure(AppControllerSource); if (AppotaSetting.UsingAdWords) AppControllerSource = AddAdWordsConfigure(AppControllerSource); var writer = new StreamWriter(fullPath, false); writer.Write(AppControllerSource); writer.Close(); }
void Update() { if(TileSettings.canUseSave == true) { grid(); TileSettings.canUseSave = false; } if(Input.GetKeyDown (KeyCode.F1) && canSave < 0) { grid(); canSave = 150; using (StreamWriter file = new StreamWriter("MapSettings2.mps")) { for(var i = 0;i < linha;i++) { for (var n = 0;n < coluna;n++) { file.WriteLine("|" + grid_type[i,n]); } } file.Close(); } } canSave--; }
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); } } }
private void Abort() { SetPage(Pages.Aborted); ABORT = true; LogLine("Aborted"); db?.Close(); }
static void Main() { string inputPath = @"..\..\input.txt"; string outputPath = @"..\..\output.txt"; StreamReader reader = new StreamReader(inputPath); StreamWriter writer = new StreamWriter(outputPath,false); int n = int.Parse(reader.ReadLine()); int[,] matrix = new int[n, n]; int maxsum = 0; for (int i = 0; i < n; i++) { string[] numbersOnThisLine = new string[n]; numbersOnThisLine = reader.ReadLine().Split(' '); for (int j = 0; j < n; j++) { matrix[i, j] = int.Parse(numbersOnThisLine[j]); } } reader.Close(); maxsum = FindMaxSum(n, matrix, maxsum); writer.WriteLine(maxsum); writer.Close(); }
/// <summary> /// 合并文件,合并到文件1 /// </summary> /// <param name="path1">文件1</param> /// <param name="path2">文件2</param> public static void ComboFile(string path1, string path2) { StreamReader sr = null; StreamWriter sw = null; try { sr = new StreamReader(path2, Encoding.Default); sw = new StreamWriter(path1, true, Encoding.Default); var str = sr.ReadLine(); while (!string.IsNullOrEmpty(str)) { sw.WriteLine(str); str = sr.ReadLine(); } } catch (Exception ex) { Logger.Error(ex.Message, ex); } finally { sr?.Close(); sw?.Close(); } }
/// <summary> /// Writes the analysis data. /// </summary> /// <param name='pathToMusicFile'> /// Path to music file. /// </param> /// <param name='peaks'> /// Array of Peaks. /// </param> /// <param name='loudParts'> /// Array of Loud parts. /// </param> public static void writeAnalysisData(string pathToMusicFile, int[][] peaks, int[] loudParts, float variationFactor) { // Open StreamWriter sw = new StreamWriter (convertToCacheFileName (pathToMusicFile)); // Write peaks to file for (int i = 0; i < peaks.Length; i++) { sw.Write ("c" + i + ":"); for (int j = 0; j < peaks[i].Length; j++) { sw.Write (peaks [i] [j]); sw.Write (';'); } sw.WriteLine (); } // Write loudness levels to file sw.Write ("lp:"); foreach (int lP in loudParts) sw.Write (lP + ";"); sw.WriteLine(); // Write variation factor to file sw.Write("vf:"); sw.Write(variationFactor); // Close sw.Flush (); sw.Close (); }
public static int Main(string[] argv) { if (argv.Length != 2) { Console.Error.WriteLine("Usage: query assembly-name output-file"); return 1; } string name = argv[0]; string outname = argv[1]; Assembly ass; try { ass = Assembly.Load(name); } catch(System.IO.IOException e) { Console.Error.WriteLine("Cannot load assembly {0}: {1}", name, e.Message); return 2; } try { outfile = new StreamWriter(outname); } catch(System.IO.IOException e) { Console.Error.WriteLine("Cannot open file {0}: {1}", outname, e.Message); return 3; } PrintAssembly(ass); outfile.Close(); return 0; }
internal static void Error(Exception ex) { var text = LogException(ex); Error(text); _mWriter?.Close(); }
private List <Plane> PerformAction(string actionName, string contentsToWriteToFile) { _waitHandle.WaitOne(); switch (actionName) { case "Read": { var planes = new JavaScriptSerializer().Deserialize <List <Plane> >(File.ReadAllText(_filePath)); _waitHandle.Set(); return(planes); } case "Write": { TextWriter writer = null; try { writer = new StreamWriter(_filePath, false); writer.Write(contentsToWriteToFile); } finally { writer?.Close(); } _waitHandle.Set(); return(null); } default: _waitHandle.Set(); return(null); } }
static void Main() { /* Problem 3. Line numbers Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file. */ StreamReader reader = new StreamReader("Read.txt"); StreamWriter writer = new StreamWriter("Write.txt"); int countLines = 0; string line = reader.ReadLine(); using (reader) { while (line != null) { countLines++; writer.WriteLine("Line number {0}: {1}", countLines, line); line = reader.ReadLine(); } } writer.Close(); }
private void DownloadWebpage() { string URL = TextBox1.Text; AutoResetEvent resultEvent = new AutoResetEvent(false); string result = null; bool visible = this.Checkbox1.Checked; IEBrowser browser = new IEBrowser(visible, URL, resultEvent); // wait for the third thread getting result and setting result event EventWaitHandle.WaitAll(new AutoResetEvent[] { resultEvent }); // the result is ready later than the result event setting sometimes while (browser == null || browser.HtmlResult == null) Thread.Sleep(5); result = browser.HtmlResult; if (!visible) browser.Dispose(); //把获取的html内容通过label显示出来 Label2.Text = result; //保存结果到本程序的目录中 string path = Request.PhysicalApplicationPath; TextWriter tw = new StreamWriter(path + @"softlab/result.html"); tw.Write(result); tw.Close(); //open a new web page to display result got from webbrowser. Response.Output.WriteLine("<script>window.open ('result.html','mywindow','location=1,status=0,scrollbars=1,resizable=1,width=600,height=600');</script>"); }
void OnGUI() { GUIStyle mgui = new GUIStyle(); mgui.fontSize = 200; if (mode == "main") GUI.DrawTexture (getRect(0.1, 0.1, 0.3, 0.1), target); else GUI.DrawTexture (getRect(0.6, 0.1, 0.3, 0.1), target); if (GUI.Button(getRect(0.1, 0.1, 0.3, 0.1), "메인 맵")) mode = "main"; if (GUI.Button(getRect(0.6, 0.1, 0.3, 0.1), "커스텀 맵")) mode = "costom"; for(int y=0;y<2;y++) { for (int x = 0; x < 5; x++) { if (GUI.Button(getRect(0.05+0.2*x, 0.3+0.2*y, 0.1, 0.1), (5 * y + x + 1).ToString())) { stage = 5 * y + x + 1; StreamWriter sw= new StreamWriter("playinfo.txt"); sw.WriteLine(mode); sw.WriteLine(stage.ToString()); sw.Close(); Application.LoadLevel("game"); } } } if (GUI.Button(getRect(0.4, 0.8, 0.2, 0.1), "돌아가기")) Application.LoadLevel("mainscreen"); }
static void Main() { StreamReader reader = new StreamReader(@"..\..\input.txt"); List<string> allEvenLines = new List<string>(); string currLine = null; while (1 == 1) { currLine = reader.ReadLine();//Line1 (1/3/5/7) currLine = reader.ReadLine();//Line2 (4/6/8/10) if (currLine == null) { break; } allEvenLines.Add(currLine); } reader.Close(); StreamWriter writer = new StreamWriter(@"..\..\input.txt", false); // after closing the reader foreach (string line in allEvenLines) { writer.WriteLine(line); } writer.Close(); }
private void WriterQueueWorker() { while (!_isRequestShutdown) { // Reopen file stream, if date was changed and we need write to another file // TODO: Remake string comparing solution to date checking (will be much faster) if (GenerateLogFileName() != _currentLogFileName) { CloseFileStream(); OpenFileStream(); } lock (_logWriterQueue) { while (_logWriterQueue.Count > 0) { var entry = _logWriterQueue.Dequeue(); _logWriter.Write(FormatLogStr(entry.Time, entry.Message, entry.Level, entry.ContextThread)); _logWriter.Flush(); } } Thread.Sleep(10); } _logWriter?.Close(); }
public virtual void StopOrCancelGeneratingDataset() { StopAllCoroutines(); commonWriter?.Flush(); commonWriter?.Close(); datasetPanel.UpdateCurrentSampleCnt(0); }
void Disconnect() { StreamReader?.Close(); StreamWriter?.Close(); NetworkStream?.Close(); TcpClient?.Close(); }
void Start() { string iniPath = "Config.xml"; Config ini = null; try { StreamReader reader = new StreamReader(Path.Combine(Application.persistentDataPath, iniPath)); XmlSerializer lectorXML = new XmlSerializer(typeof(Config)); ini = (Config)lectorXML.Deserialize(reader); reader.Close(); } catch (Exception e) { Debug.Log(e.ToString()); } if (ini == null) { try { Debug.Log("Ejecutado"); XmlSerializer xmls = new XmlSerializer(typeof(Config)); StreamWriter stream = new StreamWriter(Path.Combine(Application.persistentDataPath, iniPath)); //StreamWriter stream = new StreamWriter(iniPath); xmls.Serialize(stream, new Config("Prueba")); stream.Close(); } catch (Exception e) { Debug.Log(e.ToString()); } } }
public static void Export() { int privatise = UIHelpers.ShowYesNo("Do you want living people replaced with 'Private Person' and their details hidden"); if (privatise != UIHelpers.Cancel) { int siblingsResult = UIHelpers.ShowYesNo("Do you want to include SIBLINGS of direct ancestors in the export?"); if (siblingsResult != UIHelpers.Cancel) { int descendantsResult = UIHelpers.No; if (siblingsResult == UIHelpers.Yes) // only ask about descendants if including siblings { descendantsResult = UIHelpers.ShowYesNo("Do you want to include DESCENDANTS of siblings in the export?"); } if (descendantsResult != UIHelpers.Cancel) { _privatise = privatise == UIHelpers.Yes; _includeSiblings = siblingsResult == UIHelpers.Yes; _includeDescendants = descendantsResult == UIHelpers.Yes; try { ExportGedcomFile(); } catch (Exception ex) { UIHelpers.ShowMessage(ex.Message, "FTAnalyzer"); } finally { output?.Close(); } } } } }
public void ErrorLog(string sPathName, string sErrMsg) { StreamWriter sw = new StreamWriter(sPathName + sErrorTime, true); sw.WriteLine(sLogFormat + sErrMsg); sw.Flush(); sw.Close(); }
public ManageyourEnergy() { int i = 0; int j = 0; int T = 0; long e = 0, r = 0, n = 0; long[] v = null; StreamReader sRead = new StreamReader(new FileStream(@"E:\Practice\GCJ\file\1.in", FileMode.Open)); StreamWriter sWrite = new StreamWriter(new FileStream(@"E:\Practice\GCJ\file\1.out", FileMode.OpenOrCreate)); T = Convert.ToInt32(sRead.ReadLine()); for (i = 0; i < T; i++) { string[] tmp = sRead.ReadLine().Split(' '); e = Convert.ToInt64(tmp[0]); r = Convert.ToInt64(tmp[1]); n = Convert.ToInt64(tmp[2]); v = new long[n]; tmp = sRead.ReadLine().Split(' '); for (j = 0; j < n; j++) { v[j] = Convert.ToInt64(tmp[j]); } sWrite.WriteLine("Case #{0}: {1}", i + 1, calMax(e, r, n, v)); } sRead.Close(); sWrite.Close(); }
public static void WriteLog(string ex) { string ErrorLog_OnOff = "on"; if (ErrorLog_OnOff == "" || ErrorLog_OnOff == "on") { try { string FilePath = "ErrorReport\\"; if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } string FileName = FilePath + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; if (GetFileSize(FileName) > 1024 * 1024 * 3) { CopyToBak(FileName); } StreamWriter MySw = new StreamWriter(FileName, true); MySw.WriteLine("错误信息 : " + ex); MySw.WriteLine("\r\n*****************mxy*Error*Report*****************\r\n"); MySw.Close(); //MySw.Dispose(); } catch (Exception ex1) { throw new Exception(ex1.ToString()); } } }
private void SaveSettigns() { var settings = new Settings { Url = txtUrl.Text.Trim(), Username = txtUsername.Text.Trim(), Password = txtPassword.Text.Trim(), RunWhenStartup = chkRunWhenStartup.Checked, AutoReconnectInterval = Convert.ToInt32(updnReconnect.Value) }; var serializer = new XmlSerializer(typeof(Settings)); StreamWriter writer = null; try { writer = new StreamWriter(_configPath); serializer.Serialize(writer, settings); } catch (Exception ex) { throw new Exception(ex.Message); } finally { writer?.Close(); } }
private void speichernToolStripMenuItem_Click(object sender, EventArgs e) { List <Person> personenListe = new List <Person>(); personenListe.AddRange(PersonenManager.Ärzte); personenListe.AddRange(PersonenManager.Schwestern); personenListe.AddRange(PersonenManager.Patienten); StreamWriter writer = null; try { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Auto; string json = JsonConvert.SerializeObject(personenListe, settings); writer = new StreamWriter("Personen.txt", false); writer.Write(json); } catch (Exception msg) { MessageBox.Show(msg.Message); return; } finally { writer?.Close(); } }
static int Run(object arg) { try { switch (arg) { case MgReplayOptions mgReplay: { if (!string.IsNullOrEmpty(mgReplay.FailedRequestsFile)) { _output = new StreamWriter(mgReplay.FailedRequestsFile); } int ret = ReplayMapGuide(mgReplay); Environment.ExitCode = ret; return(ret); } case MgTileSeederOptions mgOpts: { if (!string.IsNullOrEmpty(mgOpts.FailedRequestsFile)) { _output = new StreamWriter(mgOpts.FailedRequestsFile); } int ret = RunMapGuide(mgOpts); Environment.ExitCode = ret; return(ret); } case XYZReplayOptions xyzReplay: { if (!string.IsNullOrEmpty(xyzReplay.FailedRequestsFile)) { _output = new StreamWriter(xyzReplay.FailedRequestsFile); } int ret = ReplayXYZ(xyzReplay); Environment.ExitCode = ret; return(ret); } case XYZSeederOptions xyzOpts: { if (!string.IsNullOrEmpty(xyzOpts.FailedRequestsFile)) { _output = new StreamWriter(xyzOpts.FailedRequestsFile); } int ret = RunXYZ(xyzOpts); Environment.ExitCode = ret; return(ret); } default: throw new ArgumentException(); } } finally { _output?.Close(); _output?.Dispose(); } }
public static void WriteTextFile(string sFilePathAndName, string sTextContents) { StreamWriter sw = new StreamWriter(sFilePathAndName); sw.WriteLine(sTextContents); sw.Flush(); sw.Close(); }
//Methode zum Abspeichern von Fahrzeugen (vgl. auch SpeichernUndLaden.btnSave_Click()) ///In dieser Methode wird mittels der Bibliothek Newtonsoft.Json eine SERIALISIERUNG (d.h. Umwandlung in ein abspeicherbares Format) ///der Fahrzeuge durchgeführt private void SpeichereFz() { StreamWriter sw = null; try { sw = new StreamWriter("fahrzeuge.txt"); //Mittels eines Objekts vom Typ JsonSerializerSettings kann dem Serialisierer mitgeteilt werden, dass er z.B. den Typ der ///abzuspeichernden Objekte mit abspeichert JsonSerializerSettings settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Objects; for (int i = 0; i < lbxFahrzeuge.Items.Count; i++) { if (lbxFahrzeuge.GetSelected(i)) { //Umwandlung der OOP-Objekte in Strings string umgewandeltesFz = JsonConvert.SerializeObject(FahrzeugListe[i], settings); //Abspeichern des Strings sw.WriteLine(umgewandeltesFz); } } MessageBox.Show("Speichern erfolgreich"); } catch { MessageBox.Show("Speichern fehlgeschlagen"); } finally { sw?.Close(); } }
public static bool writeFile(string events,string exceptionStr) { string ip = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"].ToString(); string ServerPath = HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"]; string errorMessage="事件源:"+ip+"\n事件缘由:"+events+"\n事件异常信息:"+exceptionStr+"\n事件发生时间:"+DateTime.Now.ToString(); StreamWriter sw = null; string path = ServerPath.ToString() + "error\\"; Encoding encod = Encoding.GetEncoding("gb2312");//设置编码 string y= DateTime.Now.ToString("yyyy"); string M = DateTime.Now.ToString("MM"); string d = DateTime.Now.ToString("dd"); string h = DateTime.Now.ToString("HH"); string m = DateTime.Now.ToString("mm"); string s = DateTime.Now.ToString("ss"); string fullFileName =path+ y+"年"+M+"月"+d+"日"+h+"时"+m+"分"+s+"秒"+ ".txt"; try //写文件 { sw = new StreamWriter(fullFileName, false, encod); sw.Write(errorMessage); sw.Flush(); return true; } catch (Exception ex) { HttpContext.Current.Response.Write(ex.Message); HttpContext.Current.Response.End(); return false; } finally { sw.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); } catch { } finally { writer?.Close(); file?.Close(); writer = null; file = null; } } }
protected void btnImport_Click(object sender, EventArgs e) { string path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text; StreamReader sr = new StreamReader(path); string strTextToSplit = sr.ReadToEnd(); strTextToSplit = strTextToSplit.Replace("\r", ""); string[] arr = strTextToSplit.Split(new char[] { '\n' }); for (int i = 0; i < arr.GetUpperBound(0); i++) { arr[i] = arr[i].Replace("Type=\"Number\"", "Type=\"String\""); if (arr[i].Substring(0, 13) == "<Row><Cell ss") arr[i] = ""; if (arr[i].Length > 50 && arr[i].Substring(0, 52) == "<Row><Cell><Data ss:Type=\"String\">Lines with Errors:") arr[i] = ""; if (arr[i].IndexOf("This Student has already") != -1) arr[i] = ""; } path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text + ".xml"; if (File.Exists(path)) { File.Delete(path); } using (StreamWriter sw = new StreamWriter(path)) { foreach (string s in arr) { sw.WriteLine(s); } sw.Close(); } sr.Close(); Response.Write("DONE"); }
public void Conversation() { try { Console.WriteLine("Connection accepted."); //Make a user-friendly StreamReader from the stream sr=new StreamReader(client.GetStream()); //Make a user-friendly StreamWriter from the stream sw=new StreamWriter(client.GetStream()); String incoming=sr.ReadLine(); while (incoming!=".") { Console.WriteLine("Message received: "+incoming); sw.WriteLine(incoming); sw.Flush(); Console.WriteLine("Message Sent back: " + incoming); incoming=sr.ReadLine(); } Console.WriteLine("Client sent '.': closing connection."); sr.Close(); sw.Close(); client.Close(); } catch (Exception e) { Console.WriteLine(e+" "+e.StackTrace); } finally { if (sr!=null) sr.Close(); if (sw!=null) sw.Close(); if (client!=null) client.Close(); } }
public static void print(string msg) { string path = @"C:\Users\Public\Desktop\Failures.txt"; TextWriter tw = new StreamWriter(path, true); tw.WriteLine(msg); tw.Close(); }
public override void Run() { mode = (Patcher.Mode)Settings.Default.PatchMode; taskInterface.SetStatus("Deleting Old Src"); if (Directory.Exists(patchedDir)) { //Delete directories' files without deleting the directories themselves. This prevents weird UnauthorizedAccessExceptions from the directory being in a state of limbo. EmptyDirectoryRecursive(patchedDir); } var removedFileList = Path.Combine(patchDir, DiffTask.RemovedFileList); var noCopy = File.Exists(removedFileList) ? new HashSet <string>(File.ReadAllLines(removedFileList)) : new HashSet <string>(); var items = new List <WorkItem>(); foreach (var(file, relPath) in EnumerateFiles(patchDir)) { if (relPath.EndsWith(".patch")) { items.Add(new WorkItem("Patching: " + relPath, () => Patch(file))); noCopy.Add(relPath.Substring(0, relPath.Length - 6)); } else if (relPath != DiffTask.RemovedFileList) { items.Add(new WorkItem("Copying: " + relPath, () => Copy(file, Path.Combine(patchedDir, relPath)))); } } foreach (var(file, relPath) in EnumerateSrcFiles(baseDir)) { if (!noCopy.Contains(relPath)) { items.Add(new WorkItem("Copying: " + relPath, () => Copy(file, Path.Combine(patchedDir, relPath)))); } } //Delete empty directories, since the directory was recursively wiped instead of being deleted. DeleteEmptyDirs(patchedDir); try { CreateDirectory(Program.logsDir); logFile = new StreamWriter(Path.Combine(Program.logsDir, "patch.log")); taskInterface.SetMaxProgress(items.Count); ExecuteParallel(items); } finally { logFile?.Close(); } cutoff.Set(DateTime.Now); if (fuzzy > 0) { taskInterface.Invoke(new Action(() => ShowReviewWindow(results))); } }
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(); }
public Routine addExerciseToRoutine(int routineID, int exerciseID) { using (var context = new Layer2Container()) { Routine rc = new Routine(); try { Routine rtn = context.Routines.Where(x => x.id == routineID).FirstOrDefault(); Exercise exc = context.Exercises.Where(x => x.id == exerciseID).FirstOrDefault(); if (rtn != null && exc != null && containsExercise(routineID, exerciseID) != true) { rtn.Exercises.Add(exc); context.Routines.ApplyCurrentValues(rtn); context.SaveChanges(); } rc = rtn; } catch (NullReferenceException e) { Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace); // write off the execeptions to my error.log file StreamWriter wrtr = new StreamWriter(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/assets/documents/" + @"\" + "error.log"), true); wrtr.WriteLine(DateTime.Now.ToString() + " | Error: " + e); wrtr.Close(); } return rc; } }
public static void LogExceptions(Exception Ex, string Page, string method) { string _SchLogs = System.Configuration.ConfigurationSettings.AppSettings["ServiceLogFolder"].ToString() + "Exceptions.txt"; StringBuilder _BuilderException = new StringBuilder(); _BuilderException.Append("***********************************" + DateTime.Now.ToString() + "***********************************"); _BuilderException.AppendLine(); _BuilderException.Append(Ex.Message.ToString()); _BuilderException.AppendLine(); _BuilderException.AppendLine(); //page _BuilderException.Append("Page :" + Page); _BuilderException.AppendLine(); _BuilderException.AppendLine(); //mehotd _BuilderException.Append("Method :" + method); _BuilderException.AppendLine(); if (Ex.InnerException != null) { _BuilderException.AppendLine(); _BuilderException.Append(Ex.InnerException.ToString()); _BuilderException.AppendLine(); _BuilderException.Append(Ex.Message.ToString()); _BuilderException.AppendLine(); } _BuilderException.Append("*****************************************************************************************************"); StreamWriter _Sche_Log = new StreamWriter(_SchLogs, true, Encoding.Default); _Sche_Log.WriteLine(_BuilderException); _Sche_Log.Close(); }
public void CloseStreams() { CsvWriter?.Flush(); StreamWriter?.Flush(); CsvWriter?.Dispose(); StreamWriter?.Close(); }
void AddToHighScore(float time) { highScoreList.Add(new KeyValuePair<string, float>(userName, time)); highScoreList.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); }); //Make sure highScoreList doesn't have too many elements if (highScoreList.Count > maxScoreCount) { //Remove the last element highScoreList.RemoveAt(highScoreList.Count - 1); } StreamWriter file=new StreamWriter(filePath); //Write the updated high score list to the file for (int i = 0; i < highScoreList.Count; i++) //Iterate through highScoreList { file.WriteLine(highScoreList[i].Key.ToString() + ":" + highScoreList[i].Value.ToString()); } file.Close(); }
static void Main(string[] args) { string filename = @"..\..\testfile.txt"; StreamReader reader = new StreamReader(filename); string row = reader.ReadLine(); int count = 0; List<string> rows = new List<string>(); while (row != null) { if (count % 2 == 0) { rows.Add(row); } row = reader.ReadLine(); count++; } reader.Close(); StreamWriter writer = new StreamWriter(filename, false); for (int i = 0; i < rows.Count; i++) { writer.WriteLine(rows[i]); } writer.Close(); }
protected override void CleanUp() { CloseStream(); StreamWriter?.Close(); OnCompletion?.Invoke(); NLogFinish(); }
public static void CreateLogFile(string message) { FileStream fileStream = null; StreamWriter streamWriter = null; try { string filePath = @"c:\Logs\"; filePath = filePath + "jpmorganLog" + "-" + DateTime.Today.ToString("dd-MM-yyyy") + "." + "txt"; if (filePath.Equals("")) { return; } FileInfo logInfo = new FileInfo(filePath); DirectoryInfo dirInfo = new DirectoryInfo(logInfo.DirectoryName ?? throw new InvalidOperationException()); if (!dirInfo.Exists) { dirInfo.Create(); } fileStream = !logInfo.Exists ? logInfo.Create() : new FileStream(filePath, FileMode.Append); streamWriter = new StreamWriter(fileStream); streamWriter.WriteLine(message); } finally { streamWriter?.Close(); fileStream?.Close(); } }
/// <summary> /// 移动文件 /// </summary> /// <param name="oldPath"></param> /// <param name="newPath"></param> /// <param name="delOld"></param> /// <returns></returns> public static bool MoveFile(string oldPath, string newPath, bool delOld) { if (!File.Exists(oldPath)) { return(false); } StreamReader sr = null; StreamWriter sw = null; try { sr = new StreamReader(oldPath); sw = new StreamWriter(newPath, false); sw.Write(sr.ReadToEnd()); } catch (Exception ex) { Logger.Error(ex.Message, ex); return(false); } finally { sr?.Close(); sw?.Close(); } if (delOld) { File.Delete(oldPath); } return(true); }
private bool loadData() { string line = " "; if (File.Exists(this.path)) { StreamReader file = new StreamReader(path); while (((line = file.ReadLine()) != null) && (line.Length > 2)) { try { ConstantsLoader.constantValues.Add((TypeConstant)Enum.Parse(typeof(TypeConstant), line.Split('=')[0]), line.Split('=')[1]); } catch (ArgumentException) { Debug.Log("An element with this key already exists."); return false; } } file.Close(); return true; } else { StreamWriter file = new StreamWriter(path); file.Close(); return false; } }
/// <summary> /// 写文件 /// </summary> /// <param name="path">文件路径</param> /// <param name="str">字符</param> /// <param name="append">是否追加</param> /// <param name="code">编码</param> public static void WriteFile(string path, IEnumerable <string> str, bool append, Encoding code) { if (_mut == null) { _mut = new Mutex(); } _mut.WaitOne(); StreamWriter sw = null; try { sw = new StreamWriter(path, append, code); foreach (var s in str) { sw.WriteLine(s); sw.Flush(); } } catch (Exception ex) { Logger.Error(ex.Message, ex); } finally { sw?.Close(); _mut.ReleaseMutex(); } }
public static bool loadData() { //Debug.Log("load"); string line = " "; Dictionary<TypeConstant, string> constantValuesTemp = new Dictionary<TypeConstant, string>(); if (File.Exists(ConstantsLoader.path)) { StreamReader file = new StreamReader(path); while (((line = file.ReadLine()) != null) && (line.Length > 2)) { try { constantValuesTemp.Add((TypeConstant)Enum.Parse(typeof(TypeConstant), line.Split('=')[0]), line.Split('=')[1]); } catch (ArgumentException) { Debug.Log("An element with this key already exists."); return false; } } file.Close(); ConstantsLoader.constantValues = constantValuesTemp; return true; } else { StreamWriter file = new StreamWriter(path); file.Close(); return false; } }
private bool isCreateJson = false;//是否进行本地加载,生成索引json文件 private void OnDestroy() { Reset(); sr?.Close(); sw?.Close(); swEventConfig?.Close(); }
private void SaveDataPoor() { Stream stream = null; StreamWriter writer = null; try { stream = File.OpenWrite(_filename); writer = new StreamWriter(stream); foreach (var item in _items) { var line = $"{item.Id},{item.Name},{item.Description},{item.Price},{(item.IsDiscontinued ? 1 : 0)}"; writer.WriteLine(line); } } catch (ArgumentException e) { //Never right! //throw e; throw; } catch (Exception e) { throw new Exception("Save failed", e); } finally { writer?.Close(); stream?.Close(); } }