public static void Write(EventRecord Record) { if (!System.IO.Directory.Exists(baseDirectory)) { System.IO.Directory.CreateDirectory(baseDirectory); } string OutputFilename = System.IO.Path.Combine(baseDirectory, string.Format("Megamind_{0}", System.DateTime.Today.ToString("yyyyMMdd"))); System.IO.FileInfo fi = new System.IO.FileInfo(OutputFilename); bool AddHeader = !fi.Exists; using (var sw = fi.AppendText()) { if (AddHeader) { sw.WriteLine(Record.GetHeader()); } if (!Record.EventTime.HasValue) { Record.EventTime = System.DateTime.Now; } sw.WriteLine(Record.ToString()); sw.Flush(); sw.Close(); } }
public static void Append2File(string fileNmae, string desc) { string path = ""; if (Application.platform == RuntimePlatform.Android) { path = Application.persistentDataPath; } else if (Application.platform == RuntimePlatform.WindowsPlayer) { path = Application.dataPath; } else if (Application.platform == RuntimePlatform.WindowsEditor) { path = Application.dataPath; } System.IO.StreamWriter sw; System.IO.FileInfo fileInfo = new System.IO.FileInfo(path.Replace("/Assets", "") + "/" + fileNmae); if (!fileInfo.Exists) { sw = fileInfo.CreateText(); } else { sw = fileInfo.AppendText(); } sw.WriteLine(desc); sw.Close(); sw.Dispose(); }
private void MakeAnalogueTextHtmlCode(AnaTextData data, string path) { System.IO.FileInfo info = new System.IO.FileInfo(path); System.IO.StreamWriter writer = File.Exists(path) ? info.AppendText() : info.CreateText(); StringBuilder code = new StringBuilder(); string div = string.Format("</div>"); //태그 고유아이디랑 텍스트 사이즈 string temp = string.Format("<div id=\"{0}\" class=\"PMS_Tag_Item ui-draggable ui-draggable-handle Text_Small {1}\"", data._id, data.FontSize); code.Append(temp); //태그 주소값이랑 소수점 자리수 temp = string.Format(" opc-tag-txt=\"{{'tag':'{0}.Value','config': {{'formats': {{'bad_q':'???','float':'{1}'}}}}}}\"", data.Tag, data.Float); code.Append(temp); //색상 temp = string.Format(" d=\"#{0}\" hh=\"#{1}\" h=\"#{2}\" l=\"#{3}\" ll=\"#{4}\" style=\"position: absolute; top: {5}px; left: {6}px; color: rgb(255, 255, 255);\"", data.FontColor, data.HHColor, data.HColor, data.LColor, data.LLColor, data.Postion.X, data.Postion.Y); code.Append(temp); //인덱스랑 view에 쓸 내용 temp = string.Format(" z-index: 5;\" > {0} </div>", data.Tag); code.Append(temp); writer.WriteLine(code.ToString()); writer.Flush(); writer.Close(); }
public string MakeHtmlTextFile(string PageName) { string localpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); localpath = string.Format(localpath + ("\\")); localpath = string.Format(localpath + "VINA PMS DRAW"); localpath = string.Format(localpath + ("\\")); StringBuilder path1 = new StringBuilder(); path1.Append(localpath); if (!Directory.Exists(path1.ToString())) { try { Directory.CreateDirectory(path1.ToString()); } catch (Exception e) { MessageBox.Show(e.ToString()); return(""); } } string srcFile = string.Format("{0}{1}.txt", localpath, PageName); System.IO.FileInfo info = new System.IO.FileInfo(srcFile); System.IO.StreamWriter writer = File.Exists(srcFile) ? info.AppendText() : info.CreateText(); writer.Flush(); writer.Close(); return(srcFile); }
public void Log(String src, String message) { FileInfo file = new FileInfo(src); StreamWriter sw = file.AppendText(); sw.WriteLine(message); sw.Close(); }
public static void Write(EventRecord Record) { if (!System.IO.Directory.Exists(baseDirectory)) { System.IO.Directory.CreateDirectory(baseDirectory); } Record.ParticipantId = ParticipantId.ToString(); Record.Col = CurrentCol; Record.Row = CurrentRow; System.IO.FileInfo fi = new System.IO.FileInfo(OutputFilename); bool AddHeader = !fi.Exists; using (var sw = fi.AppendText()) { if (AddHeader) { sw.WriteLine(Record.GetHeader()); } if (!Record.EventTime.HasValue) { Record.EventTime = System.DateTime.Now; } sw.WriteLine(Record.ToString()); sw.Flush(); sw.Close(); } }
public void SaveToFile(string fileName) { var file = new FileInfo(@fileName); var stream = file.AppendText(); this.WriteFactors(stream); stream.Close(); }
/* * FOR DEBUG ONLY */ internal void PrintGErrs(int indGlyph) { FileInfo infoFile=new FileInfo("GERRS.txt"); StreamWriter writer=infoFile.AppendText(); writer.WriteLine("===> GLYPH "+indGlyph); GErrList gerrlist=this.gerrlists[indGlyph] as GErrList; if (gerrlist!=null) { writer.WriteLine("NUMBER of ERRORS: "+gerrlist.Length); } else { writer.WriteLine("EMPTY LIST"); writer.Close(); return; } foreach (GErr gerr in gerrlist) { string str=gerr.Write(); writer.WriteLine(""); writer.WriteLine("Error: "); writer.Write(str); } writer.Close(); }
/// <summary> /// Log an error to the log file /// </summary> /// <param name="toLog">The error text to log</param> internal static void LogError(string toLog) { // Should this be logged? if(Log) { StreamWriter sw = null; try { // We want to open the file and append some text to it FileInfo file = new FileInfo(logFile); sw = file.AppendText(); sw.WriteLine(DateTime.Now); sw.WriteLine(toLog); sw.WriteLine(); sw.Flush(); } finally { if(sw != null) { sw.Close(); } } } }
static void Main(string[] args) { var sourceFile = new System.IO.FileInfo(@"C:\Users\pasca\Desktop\voc-it.mdb"); var stenoEntries = Converter.Parse(sourceFile); var filtered = stenoEntries.GroupBy(_s => _s.WinstenoStroke).Select(_g => _g.First()); Console.WriteLine("Loaded {0} entries from {1}, {2} after duplicates removal.", stenoEntries.Count(), sourceFile.Name, filtered.Count()); foreach (var duplicates in stenoEntries.GroupBy(_s => _s.WinstenoStroke).Where(_g => _g.Count() > 1)) { Console.WriteLine("Duplicate : {0}", duplicates.Key); foreach(var dup in duplicates) { Console.WriteLine("\t{0} - {1}", dup.Complete, dup.Partial); } } var ploverEntries = filtered.SelectMany(_se => PloverEntry.FromWinstenoEntry(_se)).Where(_pe=>_pe != null); var plovedFiltered = ploverEntries.GroupBy(_s => _s.Strokes.ToString()).Select(_g => _g.First()); var outFile = new FileInfo(String.Format("{0}.json", Path.GetFileNameWithoutExtension(sourceFile.FullName))); outFile.Delete(); using (var outstream = outFile.AppendText()) { outstream.Write("{\n"); foreach (var entry in plovedFiltered) { outstream.Write("\"{0}\": \"{1}\", \n", entry.Strokes, entry.Value); } outstream.Write("\"\": \"\"\n"); outstream.Write("}"); } Console.WriteLine("Written {0} entries in {1}", plovedFiltered.Count(), outFile.FullName); }
private static void OutputLogToFile(int type, string tag, string message) { #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX switch (type) { case LOG_TYPE_INFO: tag = "I: " + tag; break; case LOG_TYPE_WARNING: tag = "W: " + tag; break; case LOG_TYPE_ERROR: tag = "E: " + tag; break; } StreamWriter sw; FileInfo t = new FileInfo(Application.dataPath + "//Log.txt"); if (!t.Exists) { sw = t.CreateText(); } else { sw = t.AppendText(); } sw.WriteLine(tag + message); sw.Close(); sw.Dispose(); #endif }
public void Write(string content) { try { if (!Directory.Exists(_filePath)) { Directory.CreateDirectory(_filePath); } if (_fileName.IndexOf("/", StringComparison.Ordinal) != -1) { _fileName = _fileName.Replace("/", "-"); } string strLogName = _filePath + "\\" + _fileName; var logFile = new FileInfo(strLogName); var textFile = logFile.AppendText(); //如果日志文件大于50M if (logFile.Length < 50000000) { textFile.WriteLine(content); } textFile.Close(); } catch (Exception ex) { // } }
public string WriteLog(string s) { try { FileInfo fi = new FileInfo("J:\\_net\\sys.log"); StreamWriter sw; if (fi.Exists) sw = fi.AppendText(); else sw = fi.CreateText(); sw.WriteLine(s + "\r\n"); sw.Close(); } catch (IOException ex) { return "IO Error"; } catch (UnauthorizedAccessException ex) { return "Unauthorized Access"; } catch (SecurityException ex) { return "Security Error"; } catch (NotSupportedException ex) { return "not supported"; } return "Hello World"; }
/* * Método que cria o ficheiro, se ainda não * existir, se existir, vai acrescentar ao ficheiro * o que for enviado para o ficheiro através * da variavél que recebe, a menssagem. * */ public void escreverFicheiro(string menssagem) { FileInfo file = new FileInfo("EstatisticaLP_C#.txt"); StreamWriter Txt = file.AppendText(); Txt.WriteLine(menssagem); Txt.Close(); }
public static void PrintF(String line) { String day = DateTime.Now.ToString("yyyyMMdd"); FileInfo fileInfo = new FileInfo(Config.GetPath() + "log_"+ day + ".log"); // Console.WriteLine("PrintF"); /* 음 이것도.. UI 쓰레드에서 돌리면 부하가 걸리는구나.. 그럼 결국엔.. 이것도.. 큐에 넣었다가 쓰레드로 파일에 쓰는 작업을 해야겠네.. */ lock (locker) { /* String tmp1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); line = "[" + tmp1 + "]" + line; System.IO.StreamWriter file = new System.IO.StreamWriter(path, true); file.WriteLine(line); file.Close(); */ String tmp1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); line = "[" + tmp1 + "]" + line; using (StreamWriter FileWriter = fileInfo.AppendText()) { FileWriter.WriteLine(line); } } /* 오히려 쓰레드가 더 느리네.. 쓰레드 삭제. Thread t1 = new Thread(() => WirteFile(line)); t1.Start(); */ }
public static void Log(string content) { FileInfo logFile = new FileInfo(GetDataFile("log.txt")); using (StreamWriter logStream = logFile.AppendText()) logStream.Write(DateTime.Now.ToLongTimeString() + content + "\r\n"); }
/// <summary> /// Inicializa el archivo tambien para su escritura /// </summary> public BitWriter(string workdir) { string logFileName; logFileName = String.Concat(workdir, ConfigurationManager.AppSettings["LogFileNameFormat"]); FileInfo archivo = new FileInfo(logFileName); DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); if (archivo.Exists) { if (String.Compare(archivo.LastWriteTime.ToString("yyyyMMdd"), yesterday.ToString("yyyyMMdd")) < 0) { archivo.Delete(); logStream = archivo.CreateText(); } else { logStream = archivo.AppendText(); } } else logStream = archivo.CreateText(); logStream.WriteLine(String.Format("--- Inicio de control {0} ---", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"))); }
public static void LogSingleEvent(string logIndicationText) { StreamWriter strm; string logFileName; string workdir = ConfigurationManager.AppSettings["DirectorioTrabajo"]; logFileName = String.Concat(workdir, ConfigurationManager.AppSettings["LogFileNameFormat"]); FileInfo archivo = new FileInfo(logFileName); DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); if (archivo.Exists) { if (String.Compare(archivo.LastWriteTime.ToString("yyyyMMdd"), yesterday.ToString("yyyyMMdd")) < 0) { archivo.Delete(); strm = archivo.CreateText(); } else { strm = archivo.AppendText(); } } else strm = archivo.CreateText(); strm.WriteLine(String.Format("{0} - {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), logIndicationText)); strm.Close(); }
/// <summary> /// 日志 /// </summary> /// <param name="msg"></param> /// <param name="path"></param> public void log(string msg, string path = "C://Medical") { try { DirectoryInfo dir = new DirectoryInfo(path); if (!dir.Exists) { dir.Create(); } string filename = path + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; System.IO.FileInfo file = new System.IO.FileInfo(filename); StreamWriter writer = null; if (!file.Exists) { writer = file.CreateText(); } else { writer = file.AppendText(); } writer.Write(msg + "\r\n"); writer.Flush(); writer.Close(); } catch { } }
public FileTelemetryConsumer(FileInfo file) { _logFileName = file.FullName; var fileExists = File.Exists(_logFileName); _logOutput = fileExists ? file.AppendText() : file.CreateText(); file.Refresh(); }
private double CompressionTest(int[] RandomNumberAr, int MinBorder, int MaxBorder) { FileInfo tempFile = new System.IO.FileInfo(@"..\..\temp.bin"); StreamWriter writer = tempFile.AppendText(); foreach (int number in RandomNumberAr) { writer.Write((char)number); } writer.Close(); ProcessStartInfo psi = new ProcessStartInfo(@"..\..\lzma.exe"); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.CreateNoWindow = true; psi.StandardOutputEncoding = Encoding.GetEncoding(866); psi.Arguments = @"e ""..\..\temp.bin"" ""..\..\temp.lzma"" -d16 -lc0"; Process task = Process.Start(psi); while (!task.HasExited) { Thread.Sleep(100); } FileInfo compressedTempFile = new System.IO.FileInfo(@"..\..\temp.lzma"); double ratio = (double)compressedTempFile.Length / tempFile.Length; tempFile.Delete(); compressedTempFile.Delete(); return(ratio); }
static void writeToFile(string text) { FileInfo logFile; int day, month, year; day = DateTime.Now.Day; month = DateTime.Now.Month; year = DateTime.Now.Year; string fileName = "Logger_" + day + "_" + month + "_" + year; logFile = new FileInfo(HostingEnvironment.ApplicationPhysicalPath + @".\Logs\" + fileName); if (!logFile.Exists) { using(StreamWriter sw = logFile.CreateText()) { sw.WriteLine(DateTime.Now + " : " + text); } } else { using(StreamWriter sw = logFile.AppendText()) { sw.WriteLine(DateTime.Now + " : " + text); } } }
private void add_connection_button_Click(object sender, RoutedEventArgs e) { try { FileInfo file = new FileInfo("setting_server.txt"); if (file.Exists == true) { file.Delete(); } if (file.Exists == false) { file.Create(); } Server_Setting.DataBase = @"Data Source=" + data_sourse_textbox.Text + ";Initial Catalog=" + initial_catalog_textbox.Text + ";" + "Integrated Security=" + integrated_security_textbox.Text + ";Pooling=" + pooling_textbox.Text; StreamWriter write_text; write_text = file.AppendText(); write_text.WriteLine(Server_Setting.DataBase); write_text.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
//public ZmqContext Context { get; set; } public static void WritelineToLogFile(string line) { FileInfo fi = new FileInfo(@"c:\dev\Pipe.log"); var stream = fi.AppendText(); stream.WriteLine(line); stream.Flush(); stream.Close(); }
public void WriteLineToSelf(string line, string PathSegment) { var fi = new FileInfo(string.Format(@"c:\dev\persistence\{0}.log", PathSegment)); var stream = fi.AppendText(); stream.WriteLine("{0}~{1}", line, DateTime.Now); stream.Flush(); stream.Close(); }
public void addTextInFile(String fileName, String text) { StreamWriter writeText; // класс для записи в файл FileInfo file = new FileInfo(fileName); writeText = file.AppendText(); writeText.WriteLine(text); writeText.Close(); }
public override void Log(LoggingEntery LE) { FileInfo FI = new FileInfo(string.Format("{0}_{1}.log",LE.Sender,LE.SubSender)); TextWriter TR = FI.AppendText(); TR.WriteLine(string.Format("{0}\t{1}\t{2}",DateTime.Now,LE.EnteryType.ToString(),LE.Title)); TR.WriteLine(string.Format("{0}",LE.Message)); TR.Close(); }
internal static void WriteToFile(string message) { message = DateTime.UtcNow + ", " + message; var fileInfo = new FileInfo("./Log.log"); StreamWriter streamWriter = fileInfo.AppendText(); streamWriter.WriteLine(message); streamWriter.Close(); }
public static void ResultsToFile(string fileName) { var file = new FileInfo(@fileName); var benchReport = file.AppendText(); AverageEfficiency(); WriteResults(benchReport); benchReport.Close(); }
public static void Write2File(string outString) { FileInfo logFile = new FileInfo(outpath); logWriter = logFile.AppendText(); logWriter.WriteLine(outString); logWriter.Flush(); logWriter.Close(); logWriter.Dispose(); }
public static void HandleException( object sender, UnhandledExceptionEventArgs e ) { // do not log errors if a debugger is attached if ( !Debug && System.Diagnostics.Debugger.IsAttached ) { return; } string logDir = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ), ToolName + "Logs" ); Directory.CreateDirectory( logDir ); FileInfo logfile = new FileInfo( Path.Combine( logDir, string.Format( CultureInfo.InvariantCulture, ToolName + "ErrorLog_{0}.log", DateTime.Now.ToString( "yyyy-M-d-HH-mm-ss", CultureInfo.InvariantCulture ) ) ) ); StreamWriter logfileStream = logfile.AppendText(); logfileStream.WriteLine( DateTime.Now ); logfileStream.WriteLine( Environment.MachineName ); Exception currException = (Exception)e.ExceptionObject; Exception lastException = (Exception)e.ExceptionObject; while ( currException != null ) { lastException = currException; logfileStream.WriteLine( "Type Name: " + currException.GetType().Name ); logfileStream.WriteLine( currException.Message ); logfileStream.WriteLine(); logfileStream.WriteLine( currException.StackTrace ); logfileStream.WriteLine(); logfileStream.WriteLine(); currException = currException.InnerException; } logfileStream.Close(); string formatString = "{1} {0}{0}" + "The exception has been logged to disk at: {0}" + "{2} {0}{0}" + "Trace log file is on disk at: {0}" + "{3} {0}{0}" + "Please send an email to " + ToolOwner + " with the above files attached.{0}" + "If you would like to copy the contents of this box, use ctrl + C"; string errorMsg = string.Format( CultureInfo.InvariantCulture, formatString, Environment.NewLine, lastException.Message, logfile.FullName, ExceptionCatch.TraceFile); MessageBox.Show( errorMsg, "An Error Occured" ); Application.Current.Shutdown(); }
static void Main(string[] args) { //一次全部讀完 FileInfo file1 = new FileInfo("D:\\TestFile.txt"); StreamReader sr = file1.OpenText(); Console.WriteLine(sr.ReadToEnd()); sr.Close(); Console.ReadLine(); //一次讀取一行 FileInfo file2 = new FileInfo("D:\\TestFile.txt"); StreamReader sr2 = file2.OpenText(); while (sr2.Peek() >=0) { Console.WriteLine(sr2.ReadLine()); Console.ReadLine(); } sr2.Close(); Console.ReadLine(); //一次讀取一個字 FileInfo file3 = new FileInfo("D:\\TestFile.txt"); StreamReader sr3 = file3.OpenText(); while (sr3.Peek() >=0) { Console.WriteLine((char)sr3.Read()); } sr3.Close(); Console.ReadLine(); //將資料附加在後面 FileInfo f = new FileInfo("D:\\TestFile.txt"); StreamWriter sw = f.AppendText(); //開啟舊檔案產生streamWriter的sw物件 sw.Write("測試附加功能"); sw.Flush(); sw.Close(); //刪除檔案 FileInfo file4 = new FileInfo("D:\\TestFile.txt"); if (file4.Exists) { file4.Delete(); Console.WriteLine("刪除成功"); } else { Console.WriteLine("檔案不存在"); } }
/// <summary> /// ログ書き出し /// </summary> /// <param name="filename">Filename.</param> /// <param name="prefix">Prefix.</param> /// <param name="suffix">Suffix.</param> public void WriteLog(string filename, string prefix = "", string suffix = "") { System.IO.StreamWriter sw; System.IO.FileInfo fi; fi = new System.IO.FileInfo(filename); sw = fi.AppendText(); sw.Write(prefix + Dump() + suffix); sw.Flush(); sw.Close(); }
/// <summary> /// Initialize the logger and the log file. /// </summary> public static void Initialize() { //File stuff FileInfo dir = new FileInfo("log/Log " + DateTime.Now.ToString("dd-MM-yyyy") + ".wclog"); dir.Directory.Create(); writer = dir.AppendText(); writer.AutoFlush = true; writer.WriteLine("Log starting: " + DateTime.Now.ToString()); isReady = true; }
/// <summary> /// 保存信息 可写到公用类里 /// </summary> /// <param name="obj">第一个:保存地址;第二个:保存内容;第三个:描述</param> public static void InfoLog(object obj) { var temps = (List <string>)obj; string savapath = temps[0].ToString(); //保存地址 string content = temps[1].ToString(); //保存内容 string description = temps[2].ToString(); //描述 if (string.IsNullOrEmpty(content)) { return; } string path = savapath; //string path = savapath +"//"+ DateTime.Now.ToString("yyyyMMdd") + ".txt"; //string directory = GetMapPath("//log"); //if (string.IsNullOrEmpty(directory)) //{ // return; //} try { if (!System.IO.Directory.Exists(savapath)) { System.IO.Directory.CreateDirectory(savapath); } path = path + "//" + description + ".txt"; if (!System.IO.File.Exists(path)) { using (System.IO.StreamWriter sw = System.IO.File.CreateText(path)) { sw.WriteLine(content); sw.WriteLine(); sw.Close(); } } else { System.IO.FileInfo fileinfo = new System.IO.FileInfo(path); using (System.IO.StreamWriter sw = fileinfo.AppendText()) { sw.WriteLine(content); sw.WriteLine(); sw.Close(); } } } catch (Exception ex) { MessageLog.AddErrorLogJson("InfoLog()==>错误:", ex.ToString()); } // ClearLog(); }
public static void WriteLog(string clssWhere, string functionName, string errorInfo) { try { string m_logInfo = DateTime.Now.ToString() + " clssWhere:" + clssWhere + " functionName:" + functionName + " errorInfo:" + errorInfo; FileInfo fileInfo = new FileInfo("log.txt"); StreamWriter sw = fileInfo.AppendText(); sw.WriteLine(m_logInfo); sw.Close(); } catch { } }
///////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// public StreamWriter AccesToFile() { try { FileInfo fi = new FileInfo(buffer); return fi.AppendText(); } catch (Exception ex) { return AccesToFile(); } }
private void MakeDigitalImageHtmlCode(DigiImageData data, string path) { System.IO.FileInfo info = new System.IO.FileInfo(path); System.IO.StreamWriter writer = File.Exists(path) ? info.AppendText() : info.CreateText(); StringBuilder code = new StringBuilder(); string div = string.Format("</div>"); writer.WriteLine(code.ToString()); writer.Flush(); writer.Close(); }
public void InvalidAssembly() { FileInfo file = new FileInfo( tempFile ); StreamWriter sw = file.AppendText(); sw.WriteLine("This is a new entry to add to the file"); sw.WriteLine("This is yet another line to add..."); sw.Flush(); sw.Close(); builder.Build( new TestPackage( tempFile ) ); }
void RecordMotionData() { if (recordFrame == 0) { } else if (recordFrame == 1) { System.DateTime dt = System.DateTime.Now; recordFileName = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + "-" + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + ".csv"; System.IO.FileInfo fi = new System.IO.FileInfo(Application.dataPath + "\\" + recordFileName); recordsw = fi.AppendText(); MyLog("Start Record: " + recordFrame.ToString()); } else if (recordFrame == -1) { recordsw.Flush(); recordsw.Close(); MyLog("Stop Record [" + recordFileName + "]: " + recordFrame.ToString()); recordFrame = 0; } if (recordFrame > 0) { recordsw.Write(recordFrame.ToString()); foreach (var item in offsetTrackedList) { recordsw.Write(","); recordsw.Write(item.deviceIndex.ToString()); recordsw.Write(","); recordsw.Write(item.trackerRole.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.position.x.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.position.y.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.position.z.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.rotation.w.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.rotation.x.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.rotation.y.ToString()); recordsw.Write(","); recordsw.Write(item.targetTrans.rotation.z.ToString()); } recordsw.WriteLine(); recordFrame++; MyLog("Start Record [" + recordFileName + "]: " + recordFrame.ToString()); } }
private static TextWriter GetLogger() { FileInfo logFIle = new FileInfo("Assistant.log"); TextWriter writer; if (!logFIle.Exists) { writer = logFIle.CreateText(); } else { writer = logFIle.AppendText(); } return writer; }
public static void writeLine(string msg) { try { if (!logDirectory.Exists) { logDirectory.Create(); } if (file == null) { // System.Windows.Forms.MessageBox.Show(string.Format("c:\\{0:yyyy-MM-dd-HH:mm:ss}.log", DateTime.Now), "sss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } file.Refresh(); // System.Windows.Forms.MessageBox.Show(file.Length.ToString(), "ss"); if (!file.Exists) { file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } if (file.Length > 1024 * 10240) { //System.Windows.Forms.MessageBox.Show("sa", "ss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.WriteLine(msg); } else { sw = file.AppendText(); } sw.WriteLine(msg); sw.Flush(); // System.Windows.Forms.MessageBox.Show("sa","ss"); } catch (Exception e) { tools.log.Debug(e.ToString()); } finally{ sw.Close(); sw.Dispose(); } }
/// <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(); } } }
static void Task2() // Task № 02 Написать программу, которая при старте дописывает текущее время в файл «startup.txt». { // Task № 02 Написать программу, которая при старте дописывает текущее время в файл «startup.txt». // block declare init vars string nameFile1 = "startup"; string extFile = ".txt"; //string postfix = ""; string pathCurrStart = Directory.GetCurrentDirectory(); // current folder StringBuilder postfix = new StringBuilder(); // block executive postfix.Append(Convert.ToString(DateTime.Now.Hour) + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second) + "\n"); // Get info about file System.IO.FileInfo fi = new System.IO.FileInfo(pathCurrStart + "\\" + nameFile1 + extFile); // stream for write System.IO.StreamWriter sw; // if (fi.Exists == true) { sw = fi.AppendText(); } else { sw = fi.CreateText(); } sw.WriteLine(postfix); sw.Close(); Console.WriteLine(" That all.."); Console.WriteLine(" \n \n Screen clear after :"); ClearScr(5, 3); // end of Task № 02 }
private void MakeStaticImageHtmlCode(StaticImageData data, string path) { System.IO.FileInfo info = new System.IO.FileInfo(path); System.IO.StreamWriter writer = File.Exists(path) ? info.AppendText() : info.CreateText(); StringBuilder code = new StringBuilder(); string div = string.Format("</div>"); code.Append("<div class=\"PMS_Image_Item ui-draggable ui-draggable-handle ui-resizable\" link=\"\""); code.Append(" style=\"position: absolute; "); string position = string.Format("top: {0}px; left: {1}px; z-index: {2}; \">", data.Postion.X, data.Postion.Y, data.zindex); code.Append(position); string imagepath = string.Format("<img src=\"/symbols/{0}\" style=\"width:100%;height;100%\">", data.filename); code.Append(imagepath); string temp = string.Format("<div class=\"ui-resizable-handle ui-resizable-e\" style=\"z-index: 90;\">"); code.Append(temp); code.Append(div); code.Append(temp); code.Append(div); temp = string.Format("<div class=\"ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se\" style=\"z-index: 90;\">"); code.Append(temp); code.Append(div); code.Append(div); writer.WriteLine(code.ToString()); writer.Flush(); writer.Close(); }
//Function to write log file public static void Writefile_new(string strErrMesg, string strPath) { try { strPath = strPath + "//Log"; string LogFilename = "Log" + "_" + DateTime.Now.ToString("yyyyMMdd"); System.Data.DataSet Dsfile = new System.Data.DataSet(); if (System.IO.Directory.Exists(strPath) == false) { System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(strPath); dirinfo.Create(); CreateNewXml(ref Dsfile); Dsfile.WriteXml(strPath + " \\XmlData.xml"); System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_0.log"); System.IO.StreamWriter Tex = objfile.CreateText(); Tex.Write(strErrMesg + "\r\n"); Tex.Close(); System.GC.Collect();// return; } if (System.IO.File.Exists(strPath + "\\XmlData.xml") == true) { System.Data.DataRow[] dr; int FileIndex = 0; Dsfile.ReadXml(strPath + " \\XmlData.xml"); dr = Dsfile.Tables[0].Select("SysDate ='" + DateTime.Now.ToString("dd-MM-yyyy") + "'"); if (dr.Length > 0) { FileIndex = Convert.ToInt32(dr[0]["Sysvalue"].ToString()); } else { Dsfile.Clear(); CreateNewXml(ref Dsfile); Dsfile.WriteXml(strPath + "\\XmlData.xml"); } if (System.IO.File.Exists(strPath + "\\" + LogFilename + "_" + FileIndex + ".log")) { System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log"); if (objfile.Length > 500000) //523636 { System.IO.FileInfo objfile1 = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + (FileIndex + 1).ToString() + ".log"); System.IO.StreamWriter Tex = objfile1.CreateText(); Tex.Write(strErrMesg + "\r\n"); Tex.Close(); Dsfile.Tables[0].Rows[0]["Sysvalue"] = FileIndex + 1; Dsfile.WriteXml(strPath + "\\XmlData.xml"); System.GC.Collect(); } else { System.IO.StreamWriter Tex = objfile.AppendText(); Tex.Write(strErrMesg + "\r\n"); Tex.Close(); System.GC.Collect(); } } else { System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log"); System.IO.StreamWriter Tex = objfile.CreateText(); Tex.Write(strErrMesg + "\r\n"); Tex.Close(); System.GC.Collect(); } } else { CreateNewXml(ref Dsfile); Dsfile.WriteXml(strPath + "\\XmlData.xml"); System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + LogFilename + "_0.log"); System.IO.StreamWriter Tex = objfile.CreateText(); Tex.Write(strErrMesg + "\r\n"); Tex.Close(); System.GC.Collect(); } } catch (Exception ex) { Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex.Message); } }
static void Task1() { // Task № 01 // block declare init vars string nameFile1 = "file_txt"; string extFile = ".txt"; string textContent2; string pathCurrStart = Directory.GetCurrentDirectory(); // current folder // string vars for default string nameDef1 = ""; string nameDef3 = "Я не ропщу на трудный путь земной, \n" + "Я буйного не слушаю невежды: \n" + "Моим ушам понятен звук иной, \n" + "И сердцу голос слышится надежды \n" + "С тех пор, как Санцио передо мной \n" + "Изобразил склоняющую вежды, \n" + "И этот лик, и этот взор святой, \n" + "Смиренные и легкие одежды, \n" + "И это лоно матери, и в нем \n" + "Младенца с ясным, радостным челом, \n" + "С улыбкою к Марии наклоненной. \n" + "О, как душа стихает вся до дна! \n" + "Как много со святого полотна \n" + "Ты шлешь, мой Бог, с пречистою Мадонной!"; //string var for question text string textQuestion1 = " Enter pleas name files, and press key [Enter] \n or press key [Enter] for set default value:"; string textQuestion2 = " Enter any data , and press key [Enter] \n or press key [Enter] for set default value:"; string inputStr; nameDef1 = nameFile1; // block executive Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("*************** Run Task 1 **************************"); Console.WriteLine("* \n* Current path: \n* {0}", pathCurrStart); Console.WriteLine("* *"); Console.ForegroundColor = ConsoleColor.Gray; // get full patch + file name inputStr = GetStrFromCons(textQuestion1, nameDef1); inputStr = (inputStr.Replace('\t', ' ')).Trim(' '); // избавляемся от вкравшихся табов и пограничных пробелов nameFile1 = inputStr + extFile; inputStr = ""; //get text fo write to file inputStr = GetStrFromCons(textQuestion2, nameDef3); inputStr = (inputStr.Replace('\t', ' ')).Trim(' '); // избавляемся от вкравшихся табов и пограничных пробелов textContent2 = inputStr; inputStr = ""; // Get info about file System.IO.FileInfo fi = new System.IO.FileInfo(pathCurrStart + "\\" + nameFile1); // stream for write System.IO.StreamWriter sw; // if (fi.Exists == true) { sw = fi.AppendText(); } else { sw = fi.CreateText(); } sw.WriteLine(textContent2); sw.Close(); // shutdown countdown Console.WriteLine(" \n \n Screen clear after :"); ClearScr(7, 3); // end of Task № 01 }
void Func() { #if false //string loadPath = string.Empty; //if (!TryGetLoadPath("myText.txt", out loadPath)) { return; } // string loadPath = Application.persistentDataPath + "/" + "音ゲーのtest.txt"; string loadPath = StreamingAssetsPath + "/" + "My音ゲー.txt"; //ファイル確認 System.IO.FileInfo info = new System.IO.FileInfo(loadPath); if (info.Exists) { return; info.Delete(); } //Debug.Log("path = " + loadPath); pro.text = loadPath; //ディレクトリ string directryName = System.IO.Path.GetDirectoryName(loadPath); if (!System.IO.Directory.Exists(directryName)) { Debug.Log("Dir = " + directryName); System.IO.Directory.CreateDirectory(directryName); } System.IO.StreamWriter sw; sw = info.AppendText(); sw.WriteLine("testですよーーーーー"); sw.Flush(); sw.Close(); #endif string loadPath = Application.persistentDataPath + "/" + "Music/music_test.txt"; System.IO.FileInfo fileInfo = new System.IO.FileInfo(loadPath); //ファイルが存在するか確認 if (fileInfo.Exists) { //既にファイルが存在している場合、 //上書きするか、追加するか { //上書きなら削除 // fileInfo.Delete(); } } //必要に応じてディレクトリを生成する { string dirName = System.IO.Path.GetDirectoryName(loadPath); if (!System.IO.Directory.Exists(dirName)) { System.IO.Directory.CreateDirectory(dirName); } } // 保存先 persistentDataPath // [win] : C:/Users/HomePC/AppData/LocalLow/DefaultCompany/プロジェクト名/save_data.json // [Android] : /data/app/xxxx.apk // [ios] : /var/mobile/Applications/xxxxxx/myappname.app/Data var combinedPath = System.IO.Path.Combine(Application.persistentDataPath, "hoge.txt"); }