/// <summary> /// Запись в ЛОГ-файл /// </summary> /// <param name="str"></param> public void WriteToLog(string str, bool doWrite = true) { if (doWrite) { StreamWriter sw = null; FileStream fs = null; try { string curDir = AppDomain.CurrentDomain.BaseDirectory; fs = new FileStream(curDir + "teplouchetlog.pi", FileMode.Append, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs, Encoding.Default); if (m_vport == null) sw.WriteLine(DateTime.Now.ToString() + ": Unknown port: adress: " + m_address + ": " + str); else sw.WriteLine(DateTime.Now.ToString() + ": " + m_vport.GetName() + ": adress: " + m_address + ": " + str); sw.Close(); fs.Close(); } catch { } finally { if (sw != null) { sw.Close(); sw = null; } if (fs != null) { fs.Close(); fs = null; } } } }
public static void ConvertFormat(string strInputFile, string strOutputFile) { StreamReader sr = new StreamReader(strInputFile); StreamWriter sw = new StreamWriter(strOutputFile); string strLine = null; while ((strLine = sr.ReadLine()) != null) { strLine = strLine.Trim(); string[] items = strLine.Split(); foreach (string item in items) { int pos = item.LastIndexOf('['); string strTerm = item.Substring(0, pos); string strTag = item.Substring(pos + 1, item.Length - pos - 2); sw.WriteLine("{0}\t{1}", strTerm, strTag); } sw.WriteLine(); } sr.Close(); sw.Close(); }
protected override async void Write(Core.LogEventInfo logEvent) { var request = (HttpWebRequest) WebRequest.Create(ServerUrl); request.ContentType = "application/json; charset=utf-8"; request.Method = "POST"; var requestWriter = new StreamWriter(request.GetRequestStream()); requestWriter.Write("{ " + "\"version\": " + "\"" + "1.0" + "\",\n" + "\"host\": " + "\"" + AndroidId + "\",\n" + "\"short_message\": " + "\"" + logEvent.FormattedMessage + "\",\n" + "\"full_message\": " + "\"" + logEvent.FormattedMessage + "\",\n" + "\"timestamp\": " + "\"" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + "\",\n" + "\"level\": " + "\"" + logEvent.Level.Ordinal.ToString(CultureInfo.InvariantCulture) + "\",\n" + "\"facility\": " + "\"" + "NLog Android Test" + "\",\n" + "\"file\": " + "\"" + Environment.CurrentDirectory + "AndroidApp" + "\",\n" + "\"line\": " + "\"" + "123" + "\",\n" + "\"Userdefinedfields\": " + "{}" + "\n" + "}"); requestWriter.Close(); LastResponseMessage = (HttpWebResponse) request.GetResponse(); }
public static void Extract(Category category) { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Extract"); if(!Directory.Exists(path)) Directory.CreateDirectory(path); pset.Clear(); pdic.Clear(); string downPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Down", category.Name); string fileName = string.Format(@"{0}\{1}.txt", path, category.Name); StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8); for (int i = category.DownPageCount; i >= 1; i--) { string htmlFileName = string.Format(@"{0}\{1}.html", downPath, i); if (!File.Exists(htmlFileName)) Logger.Instance.Write(string.Format("{0}-{1}.html-not exist", category.Name, i)); StreamReader sr = new StreamReader(htmlFileName, Encoding.UTF8); string text = sr.ReadToEnd(); sr.Close(); var action = CreateAction(category.Type); if (action == null) continue; Extract(text, sw, category.Name,category.DbName, action); } sw.Close(); Console.WriteLine("{0}:Extract Data Finished!", category.Name); }
public static void WriteLog(string message) { var fileLog = Config.Global.Settings.LOG_PATH + "log_" + System.DateTime.Now.ToString("MM_dd_yyyy") + ".txt"; message = "\r\nTime: " + System.DateTime.Now.ToString("MM/dd/yyyy h:mm tt") + "\r\n" + message + "\r\n----------------------------------------------------"; FileStream fs = new FileStream(fileLog, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); try { sw.Close(); fs.Close(); // Ghi file fs = new FileStream(fileLog, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(message); sw.Close(); fs.Close(); } catch { sw.Close(); fs.Close(); } finally { sw.Close(); fs.Close(); } }
/* The Startup */ protected override void OnStart(string[] args) { /* Open a streamwriter */ StreamWriter streamWriter = new StreamWriter("Startup.txt", true); try { this.Host = new ServiceHost(typeof(EIAService), new Uri[0]); this.Host.Open(); } catch (Exception ex) { streamWriter.WriteLine(ex.ToString()); streamWriter.Flush(); streamWriter.Close(); return; } /* Spit it out */ streamWriter.WriteLine("Service up and running at:"); foreach (ServiceEndpoint serviceEndpoint in (Collection<ServiceEndpoint>)this.Host.Description.Endpoints) streamWriter.WriteLine((object)serviceEndpoint.Address); streamWriter.Flush(); streamWriter.Close(); }
private static void CommitQuizAnswers(String quizAnswers, String personName, String setupID) { XmlSerializer writer; StreamWriter quizAnswersFile = null; DataSet quizData = null; try { if (String.IsNullOrEmpty(quizAnswers)) return; quizData = RetrieveQuizAnswersData(); //Create the dataset of answers quizData.Tables[0].Rows.Add(setupID, personName, quizAnswers, DateTime.Now); writer = new XmlSerializer(typeof(DataSet)); quizAnswersFile = new StreamWriter(QuizAnswersFilePath); writer.Serialize(quizAnswersFile, quizData); quizAnswersFile.Close(); quizAnswersFile.Dispose(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in CommitQuizAnswers at Screen side {0}", ex.Message); writer = null; if (quizAnswersFile != null) { quizAnswersFile.Close(); quizAnswersFile.Dispose(); } } }
public static bool IsTemplateEnabledFor(object target, string templateName, DTE service = null) { try { var selectedItem = target as ProjectItem; if (selectedItem == null) { return false; } string selectedFolderPath = DteHelper.GetFilePathRelative(selectedItem); var templatePath = TemplateConfiguration.GetConfiguration(service).ExtRootFolderName + "\\" + templateName; var wr = new StreamWriter(@"C:\test.text", true); if (selectedFolderPath.ToLower().Contains(templatePath.ToLower())) { wr.WriteLine("SelectedFolderPath:{0}, TemplatePath:{1}, Valid", selectedFolderPath, templatePath); wr.Close(); return true; } wr.WriteLine("SelectedFolderPath:{0}, TemplatePath:{1}, Invalid", selectedFolderPath, templatePath); wr.Close(); return false; } catch (Exception ex) { MessageBox.Show(string.Format(ErrorMessages.GeneralError, ex.Message), MessageType.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } }
public static void CommitTelemetry() { XmlSerializer writer; StreamWriter telemetryFile = null; try { if (telemetryData == null) return; writer = new XmlSerializer(typeof(DataSet)); telemetryFile = new StreamWriter(TelemetryFilePath); writer.Serialize(telemetryFile, telemetryData); telemetryFile.Close(); telemetryFile.Dispose(); telemetryData = null; } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in CommitTelemetry at Screen side {0}", ex.Message); writer = null; if (telemetryFile != null) { telemetryFile.Close(); telemetryFile.Dispose(); } telemetryData = null; } }
public static Object LoadFromText(System.Type ObjectType, string XmlContent) { Object RetVal; MemoryStream Stream; StreamReader Reader; StreamWriter Writer; RetVal = null; Stream = new MemoryStream(); Reader = new StreamReader(Stream); Writer = new StreamWriter(Stream); try { if (!string.IsNullOrEmpty(XmlContent)) { Writer.Write(XmlContent); Writer.Flush(); Stream.Position = 0; RetVal = Deserialize(Reader, ObjectType); Writer.Close(); Reader.Close(); } } catch (Exception ex) { Writer.Close(); Reader.Close(); throw ex; } return RetVal; }
public static void Write(Exception e) { StreamWriter sw = null; try { if (!Directory.Exists(LOG_DIR)) { Directory.CreateDirectory(LOG_DIR); } int index = 0; string filePath = LOG_DIR + @"explog " + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; FileInfo fi = new FileInfo(filePath); while (fi.Exists && fi.Length > 1024 * 1024) { index++; filePath = LOG_DIR + @"explog " + DateTime.Now.ToString("yyyy-MM-dd") + string.Format("_{0}.txt", index); fi = new FileInfo(filePath); } sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8); sw.WriteLine(DateTime.Now.ToString() + " " + e.Message); sw.WriteLine("Source:" + e.Source); sw.WriteLine("TargetSite:" + e.TargetSite); sw.WriteLine(EnhancedStackTrace(new StackTrace(e, true))); sw.WriteLine("===================================="); sw.Close(); } catch { if (sw != null) sw.Close(); } }
public void WriteFiles(string content) { try { FileStream fi = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt", FileMode.Append); StreamWriter sw = new StreamWriter(fi, Encoding.UTF8); sw.WriteLine(content); sw.WriteLine("-------------------------------------------------------"); if (fi.Length >= (1024 * 1024 * 5)) { sw.Close(); fi.Close(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt")) { File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt"); } return; } sw.Close(); fi.Close(); } catch (Exception ex) { } }
public void SaveInfo3(string data, string filename) { StreamWriter sw = null; try { FileStream fs = File.Open(filename, FileMode.Open); sw = new StreamWriter(fs); sw.Write(data); sw.Close(); } catch (FileNotFoundException fnfex) { Console.WriteLine("File does not exist: {0}\n", fnfex.Message); } catch (Exception ex) { Console.WriteLine("Unexpected exception:{0}\n", ex.Message); } finally { if (sw != null) { sw.Close(); } } }
public static string SerializeToText(System.Type ObjectType, Object Object) { string RetVal; StreamWriter Writer; StreamReader Reader; MemoryStream Stream; RetVal = string.Empty; Stream = new MemoryStream(); Reader = new StreamReader(Stream); Writer = new StreamWriter(Stream); try { if (Object != null && ObjectType != null) { Serialize(Writer, ObjectType, Object); Stream.Position = 0; RetVal = Reader.ReadToEnd(); Writer.Flush(); Writer.Close(); Reader.Close(); } } catch (Exception ex) { Writer.Flush(); Writer.Close(); Reader.Close(); throw ex; } return RetVal; }
static void Main(string[] args) { // Создание файла. FileStream file = File.Create(@"D:\test.txt"); // 1. var writer = new StreamWriter(file); writer.WriteLine("Hello"); writer.Close(); // file.Close(); // 2. writer = File.CreateText(@"F:\test.txt"); writer.WriteLine("Hello"); writer.Close(); // 3. File.WriteAllText(@"F:\test.txt", "Hello"); // 4. file = null; file = File.Open(@"F:\test.txt", FileMode.Open, FileAccess.Write,FileShare.Write); file.Close(); // 5. file = File.OpenWrite(@"F:\test.txt"); // file.Close(); // 6. Будет исключение, так как файл занят! file = File.Open(@"F:\test.txt", FileMode.OpenOrCreate, FileAccess.Write,FileShare.Write); // file.Close(); // Файлы необходимо закрывать!!! }
static float vel_Prec = 0; // Contiene il valore della velocità all'ultimo istante della finestra precedente. #endregion Fields #region Methods // Metodo per la scrittura e creazione del .csv che contiene i dati. public static void createCsv(float[,,] sampwin, string path) { StreamWriter file = new StreamWriter(@path, true); string stream = ""; for (int s = 0; s < sampwin.GetLength(0); s++) { stream = stream + "SENSORE " + (s + 1) + ":" + "\n" + "\n"; for (int i = 0; i < sampwin.GetLength(1); i++) { for (int j = 0; j < sampwin.GetLength(2); j++) { stream = stream + sampwin[s, i, j].ToString() + ";"; } stream = stream + "\n"; } stream = stream + "\n"; try { file.Write(stream); stream = ""; } catch (Exception e) { file.Close(); stream = ""; } } file.Close(); }
static void Game_OnChat(GameChatEventArgs args) { if (!main.Item("enabled").GetValue<bool>()) return; try{ var stream = new StreamWriter(_path, true, Encoding.UTF8); if (args.Sender.IsAlly) { stream.WriteLine("[" + Utils.FormatTime(Game.ClockTime) + "]" + " sender: " + args.Sender.Name + " says: " + args.Message); stream.Close(); } else { stream.WriteLine("[" + Utils.FormatTime(Game.ClockTime) + "]" + "[enemy] sender: " + args.Sender.Name + " says: " + args.Message); stream.Close(); } if (main.Item("notify").GetValue<bool>()) Notifications.AddNotification(new Notification("Chat loged",500).SetBoxColor(Color.Black).SetTextColor(Color.Green)); if (main.Item("delay").GetValue<int>()!=0) System.Threading.Thread.Sleep(main.Item("delay").GetValue<int>()); } catch (Exception e) { //Notifications.AddNotification("ChatLog error: " + e.Message,1000); } }
/// <summary> /// Exports an answer matrix to a file. /// </summary> /// <param name="answerMatrix">Answer matrix</param> /// <param name="filename">Output file path</param> public static void Export(TLSimilarityMatrix answerMatrix, string filename) { TextWriter tw = null; try { tw = new StreamWriter(filename); foreach (string sourceID in answerMatrix.SourceArtifactsIds) { tw.Write(sourceID); foreach (string targetID in answerMatrix.GetSetOfTargetArtifactIdsAboveThresholdForSourceArtifact(sourceID)) { tw.Write(" " + targetID); } tw.WriteLine(); } tw.Flush(); tw.Close(); } catch (Exception e) { if (tw != null) { tw.Close(); } throw new DevelopmentKitException("There was an exception writing to file (" + filename + ")", e); } }
public void addLog(string method, string kind, string msg, LogType logType) { string localPath = ""; string logPath = AppDomain.CurrentDomain.BaseDirectory + "log/" + logType.ToString() + "/"; localPath = string.Format(logPath + "{0:yyyyMMdd}.log", DateTime.Now); lock (localPath) { StreamWriter writer = null; try { System.IO.FileInfo info = new FileInfo(localPath); if (!info.Directory.Exists) info.Directory.Create(); writer = new StreamWriter(localPath, true, System.Text.Encoding.UTF8); writer.WriteLine(string.Format("{0}[{1:HH:mm:ss}] 方法{2} 用户:{3}[end]", kind, DateTime.Now, method, msg)); } catch { if (writer != null) writer.Close(); } finally { if (writer != null) writer.Close(); } } }
public void pingHost(string hostName, int pingCount) { if (pingCount == 0) { pingCount = 43200; } Console.WriteLine("Host, Response Time, Status, Time "); String fileName = String.Format(@"tping-{0}-{1}-{2}-{3}.csv", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); for (int i = 0; i < pingCount; i++) { Ping ping = new Ping(); StreamWriter processedData = new StreamWriter(@fileName, true); try { PingReply pingReply = ping.Send(hostName); processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status); processedData.Close(); Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status); } catch (System.Net.NetworkInformation.PingException) { processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error"); Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error"); processedData.Close(); //Console.WriteLine(Ex); //Environment.Exit(0); } Thread.Sleep(2000); } Console.WriteLine("\n" + "tping complete - {0} pings logged in {1}", pingCount, fileName); }
//导出到Excel public static void exportDgvToExcel(DataGridView dgv) { SaveFileDialog saveFileDlg = new SaveFileDialog(); saveFileDlg.Filter = "Execl files (*.xls,*.xlsx)|*.xls"; saveFileDlg.FilterIndex = 0; saveFileDlg.RestoreDirectory = true; saveFileDlg.CreatePrompt = true; saveFileDlg.Title = "Export Excel File To"; if (saveFileDlg.ShowDialog() != DialogResult.OK) return; Stream myStream; myStream = saveFileDlg.OpenFile(); //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try { //写标题 for (int i = 0; i < dgv.ColumnCount; i++) { if (!dgv.Columns[i].Visible) continue; if (i > 0) { str += "\t"; } str += dgv.Columns[i].HeaderText; } sw.WriteLine(str); //写内容 for (int j = 0; j < dgv.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < dgv.Columns.Count; k++) { if (!dgv.Columns[k].Visible) continue; if (k > 0) { tempStr += "\t"; } if (dgv.Rows[j].Cells[k].Value != null) tempStr += dgv.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); } }
protected void Page_Load(object sender, EventArgs e) { try { #region if (Request.QueryString["id"] == null || Request.QueryString["id"].ToString() == "") { return; } if (Request.QueryString["users"] == null || Request.QueryString["users"].ToString() == "") { return; } if (Request.QueryString["fid"] == null || Request.QueryString["fid"].ToString() == "") { return; } #endregion string id = ""; int count = 0; int start = 0; string cur_group = Request.QueryString["id"].ToString() + "-" + Request.QueryString["users"].ToString() + "|" + Request.QueryString["fid"].ToString(); //2-fanzjg,admin,bryan,i_am_tbag|161 string str_path = HttpContext.Current.Server.MapPath("~/Users.txt"); reader = new StreamReader(str_path); sLine = reader.ReadToEnd().Trim(); string[] groups = sLine.Split('\n'); for (int i = 0; i < groups.Length; i++) { id = groups[i].Split('|')[0].Split('-')[0].ToString().Trim(); if (id == Request.QueryString["id"].ToString()) { start = sLine.IndexOf(id); count = cur_group.Length; } } reader.Close(); writer = new StreamWriter(str_path); sLine = sLine.Remove(start, count); writer.Write(sLine); writer.Close(); Response.Redirect("setuser.aspx"); } catch (Exception ex) { ex.Message.ToString(); } finally { reader.Close(); writer.Close(); } }
/// <summary> /// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。 /// </summary> /// <remarks> /// using System.IO; /// </remarks> /// <param name="dgv"></param> public static void DataGridViewToExcel(DataGridView dgv) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存为Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dgv.ColumnCount; i++) { if (i > 0) { columnTitle += "\t"; } columnTitle += dgv.Columns[i].HeaderText; } sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dgv.Rows.Count; j++) { string columnValue = ""; for (int k = 0; k < dgv.Columns.Count; k++) { if (k > 0) { columnValue += "\t"; } if (dgv.Rows[j].Cells[k].Value == null) columnValue += ""; else columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim(); } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } }
/// <summary> /// 测试向创建文本文件,并向其中写入文本信息. /// </summary> public void TestWrite() { Console.WriteLine("写入文本文件信息开始!"); StreamWriter sw = null; try { // 首先判断,文件是否已经存在 if (File.Exists(TEXT_FILE_NAME)) { // 如果文件已经存在,那么删除掉. File.Delete(TEXT_FILE_NAME); } // 注意第2个参数: // 确定是否将数据追加到文件。如果该文件存在,并且 append 为 false,则该文件被覆盖。 // 如果该文件存在,并且 append 为 true,则数据被追加到该文件中。否则,将创建新文件。 // 也就是说,如果第2个参数 是 false, 可以不用写前面的 判断文件存在则删除的代码. // 第3个参数为编码方式, 读取和写入,尽可能使用统一的编码 sw = new StreamWriter(TEXT_FILE_NAME, false, Encoding.UTF8); // 写入测试数据. sw.WriteLine("这是一个文本文件的 写入/读取 例子……"); sw.WriteLine("这是第二行"); sw.WriteLine("后面没有了……"); // 关闭文件. sw.Close(); sw = null; } catch (Exception ex) { Console.WriteLine("在写入文件的过程中,发生了异常!"); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { if (sw != null) { try { sw.Close(); } catch { // 最后关闭文件,无视 关闭是否会发生错误了. } } } Console.WriteLine("写入文本文件信息结束!"); }
public static void Output(DataTable dt, string fileName) { Stream myStream = File.Open(fileName,FileMode.Create,FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dt.Columns.Count; i++) { if (i > 0) { columnTitle += "\t"; } columnTitle += dt.Columns[i].ColumnName; } sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dt.Rows.Count; j++) { string columnValue = ""; for (int k = 0; k < dt.Columns.Count; k++) { if (k > 0) { columnValue += "\t"; } if (dt.Rows[j][k] == null) columnValue += ""; else { if (dt.Rows[j][k].GetType() == typeof(string) && dt.Rows[j][k].ToString().StartsWith("0")) { columnValue += "'" + dt.Rows[j][k].ToString(); } else columnValue += dt.Rows[j][k].ToString(); } } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); } catch (Exception ex) { throw; } finally { sw.Close(); myStream.Close(); } }
private void buttonAdd_Click(object sender, EventArgs e) { StreamWriter sr = new StreamWriter("test.txt", true); if(textBoxEng.Text != "" && textBoxRus.Text != "") { sr.WriteLine(textBoxEng.Text + " - " + textBoxRus.Text); sr.Close(); textBoxEng.Text = ""; textBoxRus.Text = ""; } else sr.Close(); }
// 0: succes, 1: error, 2: no movement in file public int WriteVideo(ProgressStorage progressStorage) { int movementSomewhere = 1; // create txt file that will be used to join all videos temporaryFiles = new List<String>(); String txtPath = outputfolder + "\\output_temptxtfile.txt"; temporaryFiles.Add(txtPath); // add to files that will be removed after execution StreamWriter outputtxt = new StreamWriter(txtPath, false); // convert to mp4 in original quality, create subparts and add then to the outputtxt for (int i = 0; i < filelist.Length; i++) { String toDeleteFile = convertPart(filelist[i]); // no result needed, because if this failed, next one will fail as well int result = cutParts(toDeleteFile, trackerlist[i], outputtxt); if(result == 1) // it failed { // remove all temporary objects here (close txt first) outputtxt.Close(); clearFiles(temporaryFiles); progressStorage.resetGeneration(); // update progressStorage return 1; // something failed } else if (result == 0) { // if we get in to this part at least once, it means there is movement in some of the files movementSomewhere = 0; } clearFile(toDeleteFile); // delete temp file progressStorage.generationFileFinished(); // update progressStorage } int result2; outputtxt.Close(); if(movementSomewhere == 0) { // execute the command to join the subfiles result2 = joinParts(txtPath); } else { result2 = 2; } // remove all temporary files clearFiles(temporaryFiles); if(result2 != 1) { progressStorage.generationFileFinished(); // update progressStorage } else { progressStorage.resetGeneration(); // update progressStorage } return result2; }
/// <summary> /// This program is used at compile-time by the NSIS Install Scripts. /// It copies the file properties of an assembly and writes that info a /// header file that the scripts use to make the installer match the program /// /// I got it from <http://stackoverflow.com/questions/3039024/nsis-put-exe-version-into-name-of-installer#3040323> /// </summary> static void Main(string[] args) { try { string inputFile = args[0]; string outputFile = args[1]; System.Diagnostics.FileVersionInfo fileInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(inputFile); using (TextWriter writer = new StreamWriter(outputFile, false, Encoding.Default)) { writer.WriteLine("!define VERSION \"" + fileInfo.FileVersion + "\""); writer.WriteLine("!define DESCRIPTION \"" + fileInfo.FileDescription + "\""); writer.WriteLine("!define COPYRIGHT \"" + fileInfo.LegalCopyright + "\""); writer.Close(); } string xmlFile = "version.xml"; XmlWriterSettings xws = new XmlWriterSettings(); xws.CloseOutput = true; xws.ConformanceLevel = ConformanceLevel.Document; xws.Indent = true; xws.WriteEndDocumentOnClose = true; using (XmlWriter writer = XmlWriter.Create(xmlFile)) { writer.WriteStartDocument(); writer.WriteStartElement("RedBrick"); writer.WriteStartElement("version"); writer.WriteString(fileInfo.FileVersion); writer.WriteEndElement(); writer.WriteStartElement("url"); writer.WriteString(@"file://\\AMSTORE-SVR-02\shared\shared\general\RedBrick\InstallRedBrick.exe"); writer.WriteEndElement(); string update_message = string.Empty; using (TextReader tr = new StreamReader(Properties.Settings.Default.MessagePath)) { update_message = tr.ReadToEnd(); } writer.WriteStartElement("message"); writer.WriteString(update_message); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } } catch (Exception e) { Console.WriteLine(e.Message + "\n\n"); Console.WriteLine("Usage: GetAssemblyInfoForNSIS.exe MyApp.exe MyAppVersionInfo.nsh\n"); } }
//ͬ����ʽ����http post���� public string HttpPost(string url, string queryString) { StreamWriter requestWriter = null; StreamReader responseReader = null; string responseData = null; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ServicePoint.Expect100Continue = false; webRequest.Timeout = 20000; try { //POST the data. requestWriter = new StreamWriter(webRequest.GetRequestStream()); requestWriter.Write(queryString); requestWriter.Close(); requestWriter = null; responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch { throw; } finally { if (requestWriter != null) { requestWriter.Close(); requestWriter = null; } if (responseReader != null) { responseReader.Close(); responseReader = null; } webRequest.GetResponse().GetResponseStream().Close(); webRequest = null; } return responseData; }
private void button1_Click(object sender, EventArgs e) { if (textBox1.TextLength != 0) { string file = Path.Combine(BESFolder, textBox1.Text + ".cbes"); if (File.Exists(file)) File.Delete(file); StreamWriter writer = new StreamWriter(file); writer.WriteLine(form.GetInitial()); writer.WriteLine(form.GetExpand()); writer.WriteLine(form.GetRounds()); writer.WriteLine(form.GetLeftoff()); writer.WriteLine(form.GetKey()); writer.WriteLine(form.GetCipherMode()); writer.WriteLine(form.GetSeedFunction()); writer.WriteLine(form.GetGenerationMode()); writer.Close(); writer.Dispose(); RefreshElements(); this.Close(); } }
private void Form1_Closing(object sender, CancelEventArgs e) { if (xBCScanner != null) { xBCScanner.Dispose(); } // сохранение рабочих данных (если есть) if (bGoodAvtor == true) { //xNSI.SaveCS(xSm, xPars); xSm.SaveCS(xPars.sDataPath, xNSI.DT[NSI.TBD_DOC].dt.Rows.Count); xNSI.DSSave(xPars.sDataPath); } if (swProt != null) { swProt.Close(); } }
public static System.Net.Mail.Attachment GetAttachmentFromString(string fileName, string content) { using (MemoryStream contentStream = new System.IO.MemoryStream()) using (System.IO.StreamWriter writer = new System.IO.StreamWriter(contentStream)) { writer.Write(content); writer.Flush(); writer.Close(); // reset stream position contentStream.Position = 0; ContentType contentType = new ContentType(MediaTypeNames.Text.Plain); var attachment = new System.Net.Mail.Attachment(contentStream, contentType); attachment.ContentDisposition.FileName = fileName; contentStream.Close(); return(attachment); } }
private void RemoveStringInBackup(int number) { string[] readText = System.IO.File.ReadAllLines(this.pathFileLog); File.Delete(this.pathFileLog); FileInfo fileLog = new FileInfo(this.pathFileLog); FileStream fs = fileLog.Create(); fs.Close(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(this.pathFileLog, false)) { for (int i = 0; i < number * 4; i++) { file.WriteLine(readText[i]); } file.Close(); } }
public void SaveFile(string fileName) { try { CleanUpConnectionInfo(); _fileName = fileName; XmlSerializer writer = new XmlSerializer(typeof(ComparisonInfo)); StreamWriter file = new System.IO.StreamWriter(fileName); _comparison.RefreshSkipSelectionsFromComparisonObjects(); writer.Serialize(file, _comparisonInfo); file.Close(); } catch (Exception exc) { MessageBox.Show($"Error saving file {fileName}\n{exc.Message}", Utils.AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// Pour sauvegarder dans un fichier texte public void Save(bool append = false) { int i = 0; System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, append); foreach (SaveTransform t in SaveTransforms) { // On le numéro de la sauvegarde, le temps et sa rotation sw.WriteLine("#" + i); sw.WriteLine(t.time); sw.WriteLine(t.rot.x); sw.WriteLine(t.rot.y); sw.WriteLine(t.rot.z); sw.WriteLine(t.rot.w); i += 1; } sw.Close(); }
public virtual void SaveToFile(string fileName, System.Text.Encoding encoding) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(encoding); streamWriter = new System.IO.StreamWriter(fileName, false, encoding); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } }
private void button6_Click(object sender, EventArgs e) { var item = this.listBox1.SelectedItem; if (item == null) { return; } var inx = this.listBox1.SelectedIndex; var info = list[inx]; using (System.IO.StreamWriter sw = new System.IO.StreamWriter("list.db", true)) { sw.WriteLine(item.ToString()); sw.WriteLine(string.Format("{0}:{1}", info.IP, info.Port)); sw.Close(); } }
/// <summary> /// Triggered when "Save" (from File option) is clicked /// Intention is to allow document to be saved /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveToolStripMenuItem_Click(object sender, EventArgs e) { //Simply writing to a previously opened txt file if (fileOpen) { try { System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName); //open the file for writing. writer.Write(textBox1.Text); writer.Close(); writer.Dispose(); } catch (Exception ex) { MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" + $"Details:\n\n{ex.StackTrace}"); } } }
public void ExportToJson(string savedFileName = null) { if (savedFileName == null) { savedFileName = defaultPathAndFileName; } string jsonString = JsonConvert.SerializeObject(this.project, Newtonsoft.Json.Formatting.Indented); if (!Directory.Exists(applicationDataPath + "/data/")) { Directory.CreateDirectory(applicationDataPath + "/data/"); } FileStream fs = new FileStream(savedFileName, FileMode.Create); StreamWriter sw = new System.IO.StreamWriter(fs); sw.Write(jsonString); sw.Close(); }
public void Sort() { string file_names = Application.dataPath + "/names.txt"; string[] readNames = System.IO.File.ReadAllLines(file_names); Array.Sort(readNames); using (System.IO.StreamWriter fileN = new System.IO.StreamWriter(file_names, false)) { for (int j = 0; j < readNames.Length; j++) { fileN.WriteLine(readNames[j]); } fileN.Close(); } }
/// <summary> /// Serializes current Root object into file /// </summary> // <param name="fileName">full path of outupt xml file</param> // <param name="exception">output Exception value if failed</param> // <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); System.IO.StreamWriter streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); return(true); } catch (System.Exception e) { exception = e; return(false); } }
void Writer(string name, params object[] objs) { var ks = new List <object>(); ks.Add(name); ks.AddRange(objs); if (String.IsNullOrEmpty(path)) { WriteLine(Console.Out, ks.ToArray()); } else { var writer = new System.IO.StreamWriter(this.path, true); WriteLine(writer, ks.ToArray()); writer.Flush(); writer.Close(); } }
/// <summary> /// 防止乱码方法 /// </summary> /// <param name="strFilePath"></param> private void TransHTMLEncoding(string strFilePath) { try { System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, Encoding.GetEncoding(0)); string html = sr.ReadToEnd(); sr.Close(); html = System.Text.RegularExpressions.Regex.Replace(html, @"<meta[^>]*>", "<meta http-equiv=Content-Type content='text/html; charset=gb2312'>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false, Encoding.Default); sw.Write(html); sw.Close(); } catch (Exception ex) { //Page.RegisterStartupScript("alt", "<script>alert('" + ex.Message + "')</script>"); } }
private void Save() { Microsoft.Win32.SaveFileDialog fDialog = new Microsoft.Win32.SaveFileDialog(); fDialog.Filter = "Config Files|*.xml"; if (fDialog.ShowDialog() == true) { System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Config)); System.IO.StreamWriter file = new System.IO.StreamWriter(fDialog.FileName); PopulateConfig(isServer); writer.Serialize(file, m_config); file.Close(); ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]).SetConfigFile( fDialog.FileName); } }
void LogRun(string message) { try { string filename = DateTime.Now.ToString("dd-MMM-yyyy") + ".txt"; Console.WriteLine(message); using (System.IO.StreamWriter writer = new System.IO.StreamWriter(Request.PhysicalApplicationPath + filename, true, Encoding.Default)) { writer.WriteLine(DateTime.Now.ToString() + ":" + message); writer.Flush(); writer.Close(); } } catch (Exception e) { ErrorMessage = e.Message; } }
internal void WritePartitions(string Path) { string DirPath = System.IO.Path.GetDirectoryName(Path); if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); } XmlSerializer x = new XmlSerializer(typeof(GPT), ""); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); System.IO.StreamWriter FileWriter = new System.IO.StreamWriter(Path); x.Serialize(FileWriter, this, ns); FileWriter.Close(); }
private void btnClose_Click(object sender, EventArgs e) { string line = ""; int ndx = 0; //-- write the array back to the file System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\sds admin\\Source\\Repos\\JobTracker\\JobTracker\\JobTracker\\KeyWords.txt"); while ((Variables.kwList[ndx, 0] != null) & (ndx < 200)) { file.WriteLine(Variables.kwList[ndx, ROLE] + "," + Variables.kwList[ndx, KW]); ndx++; } //-- close the file file.Close(); //-- close the form this.Close(); }
private void setHomeLogoToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog fbd = new OpenFileDialog(); string sSelectedFile = ""; if (fbd.ShowDialog() == DialogResult.OK) { sSelectedFile = fbd.FileName; homelogopath = sSelectedFile; System.IO.StreamWriter writer = new System.IO.StreamWriter("c:/temp/homepfad.txt"); writer.Write(sSelectedFile); writer.Close(); writer.Dispose(); FileStream imageStreamHome = new FileStream(homelogopath, FileMode.Open, FileAccess.Read); scb.pBHome.Image = System.Drawing.Image.FromStream(imageStreamHome); } }
public static void SaveToFile(Collada obj, string fileName, System.Text.Encoding encoding) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(obj, encoding); streamWriter = new System.IO.StreamWriter(fileName, false, Encoding.UTF8); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } }
private void tsbShowLogs_Click(object sender, EventArgs e) { string logText = File.ReadAllText(Application.StartupPath + "\\Logs\\" + lbLogFiles.Text); //string log= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type = \"text/xsl\" href = \"logs.xsl\" ?>"; //log += "<logs>"+logText+ "</logs>"; //webBrowser1.DocumentText= log; string tempLogFile = Application.StartupPath + "\\temp_logs.xml"; System.IO.StreamWriter file = new System.IO.StreamWriter(tempLogFile); file.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type = \"text/xsl\" href = \"logs.xsl\" ?> "); file.WriteLine("<logs>"); file.WriteLine(logText); file.WriteLine("</logs>"); file.Close(); webBrowser1.Navigate(tempLogFile); }
/// <summary> /// Returns a NULL string on error, else a copy of what was written to the log file. /// </summary> /// <param name="sPrefix">What you want to place BEFORE the log entry (e.g. ClassicTime())</param> /// <param name="log">The governing instance (log file, etc)</param> /// <param name="sMessage">The message to write to the log.</param> /// <returns>The pattern written. String is null on error.</returns> static public string Log(string sPrefix, ref SimpleLog log, string sMessage) { string sFinal = sPrefix + " [" + log.sHost + "." + log.sProcessId + "]" + ": " + sMessage; try { System.IO.StreamWriter sw = File.AppendText(log.sLogFile); sw.WriteLine(sFinal); sw.Flush(); sw.Close(); } catch (Exception) { sFinal = null; return(sFinal); } return(sFinal); }
static void bot_Error(object sender, MessageEventsArgs e) { Bot tmp = (Bot)sender; if (!System.IO.Directory.Exists("Logs")) { System.IO.Directory.CreateDirectory("Logs"); } CultureInfo culture = new CultureInfo("de-DE"); Console.WriteLine(DateTime.Now.ToString() + " " + tmp.Account.Settings.Username + "(" + tmp.Account.Settings.Server + "): " + "Error ist aufgetretten"); System.IO.StreamWriter writer = new System.IO.StreamWriter(String.Concat("Logs/", tmp.Account.Settings.Server, "-", tmp.Account.Settings.Username, "-error-", DateTime.Now.ToString(culture).Remove(DateTime.Now.ToString(culture).Length - 9), ".log"), true); writer.WriteLine(DateTime.Now.ToString() + ": " + e.Message); writer.Close(); writer.Dispose(); }
private void WriteFileContent() { try { File.Delete(Path.GetDirectoryName(Application.ExecutablePath) + @"\Backup_SavedLocationData.txt"); File.Copy(Path.GetDirectoryName(Application.ExecutablePath) + @"\SavedLocationData.txt", Path.GetDirectoryName(Application.ExecutablePath) + @"\Backup_SavedLocationData.txt"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(Path.GetDirectoryName(Application.ExecutablePath) + @"\SavedLocationData.txt", false)) { file.WriteLine(SerializeToXml(lstLocation)); file.Close(); } } catch (Exception ex) { MessageBox.Show("The file could not be written: " + ex.Message); } }
/// <summary> /// 写日志 /// </summary> /// <param name="logFileName">文件名 绝对目录</param> /// <param name="strings">消息</param> public static void Write(string logFileName, string strings) { string _path = logFileName; try { if (!System.IO.File.Exists(_path)) { System.IO.FileStream f = System.IO.File.Create(_path); f.Close(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(_path, true, System.Text.Encoding.GetEncoding("gb2312"));//gb2312//UTF-8 f2.WriteLine(strings); f2.Close(); f2.Dispose(); } catch {} }
public static string XMLToString <T>(T obj) { try { MemoryStream mem = new MemoryStream(); System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); System.IO.StreamWriter file = new System.IO.StreamWriter(mem); writer.Serialize(file, obj); string result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length); file.Close(); return(result); } catch (Exception ex) { throw ex; } }
/// <summary> /// write trace log /// </summary> /// <param name="msg">message</param> /// <param name="ex">Exception</param> /// <remarks></remarks> private static void WriteTraceLog(String msg, Exception ex) { try { // make folder DateTime dt = DateTime.Now; String logFolder = System.AppDomain.CurrentDomain.BaseDirectory + "Log"; System.IO.Directory.CreateDirectory(logFolder); // touch log file String logFile = logFolder + "\\TraceLog" + dt.ToString("yyyyMMdd") + ".log"; // delete old log String logNext = logFolder + "\\TraceLog" + dt.AddDays(1).ToString("dd") + ".log"; System.IO.File.Delete(logNext); // log string String logStr; logStr = dt.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + msg; if (ex != null) { logStr = logStr + "\n" + ex.ToString(); } // Shift-JIS output System.IO.StreamWriter sw = null; try { sw = new System.IO.StreamWriter(logFile, true, System.Text.Encoding.GetEncoding("GBK")); sw.WriteLine(logStr); } catch { } finally { if (sw != null) { sw.Close(); } } } catch { } }
public void Initialize(int n, string outputFolder) { provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; StaticVectorModel[] models = new StaticVectorModel[n]; Vector <double>[] X = new Vector <double> [n]; Vector <double>[] Y = new Vector <double> [n]; Vector <double>[] Xinv = new Vector <double> [n]; Vector <double>[] YXinv = new Vector <double> [n]; for (int i = 0; i < n; i++) { models[i] = new StaticVectorModel(Phi, InvPhi, W, Nu); X[i] = models[i].X; Y[i] = models[i].Y; Xinv[i] = models[i].Xinv; YXinv[i] = models[i].YXinv; } Kxx = Exts.Cov(X, X); Kxy = Exts.Cov(X, YXinv); Kyy = Exts.Cov(YXinv, YXinv); My = YXinv.Average(); P = Kxy * (Kyy.PseudoInverse()); Kxy_inv = Exts.Cov(X, Xinv); Kyy_inv = Exts.Cov(Xinv, Xinv); My_inv = Xinv.Average(); P_inv = Kxy_inv * (Kyy_inv.PseudoInverse()); Kxy_lin = Exts.Cov(X, Y); Kyy_lin = Exts.Cov(Y, Y); My_lin = Y.Average(); P_lin = Kxy_lin * (Kyy_lin.PseudoInverse()); utStaticEstimate = new UTStaticEstimate(UTDefinitionType.ImplicitAlphaBetaKappa, OptimizationMethod.NelderMeed); utStaticEstimate.EstimateParameters(Phi, x => x.Trace(), X, Y, MX, KX, KNu, outputFolder); //utStaticEstimate.utParams = new UTParams(2, 0.5, 2.0, 1.0); using (System.IO.StreamWriter outputfile = new System.IO.StreamWriter(Path.Combine(outputFolder, "UTStaticEstimateParams.txt"))) { outputfile.WriteLine(utStaticEstimate.utParams.ToString()); outputfile.Close(); } }
public void LogMachinesData(List<Machine> machines) { // Buffer Queue string line = (Time.time - _logStartTimeMachine).ToString(); foreach (var machine in machines) { line += ";\t" + machine.pastaBufferQueue.Count; } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_machine + _logName_machineQueueFill, true)) { log_machine.WriteLine(line); log_machine.Close(); } // Breake Chance line = (Time.time - _logStartTimeMachine).ToString(); foreach (var machine in machines) { line += ";\t" + Math.Round(machine.CurrentBreakingChance, 3); } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_machine + _logName_machineBreakeChance, true)) { log_machine.WriteLine(line); log_machine.Close(); } // Broken\NotBroken line = (Time.time - _logStartTimeMachine).ToString(); foreach (var machine in machines) { line += ";\t" + (machine.IsBroken == true ? 1 : 0); } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_machine + _logName_machineBroken, true)) { log_machine.WriteLine(line); log_machine.Close(); } }
public void LogStorehouseData(List<Storehouse> storehouses) { // Queue string line = (Time.time - _logStartTimeStorehouse).ToString(); foreach (var storehouse in storehouses) { line += ";\t" + storehouse.storageQueue.Count; } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_storehouse + _logName_storehouseQueueFill, true)) { log_machine.WriteLine(line); log_machine.Close(); } // fine pasta particles line = (Time.time - _logStartTimeMachine).ToString(); foreach (var storehouse in storehouses) { line += ";\t" + storehouse.fineParticlesCounter; } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_storehouse + _logName_storehouseFineParticles, true)) { log_machine.WriteLine(line); log_machine.Close(); } // damaged pasta particles line = (Time.time - _logStartTimeMachine).ToString(); foreach (var storehouse in storehouses) { line += ";\t" + storehouse.damagedParticlesCounter; } using (System.IO.StreamWriter log_machine = new System.IO.StreamWriter(_logAddres_storehouse + _logName_storehouseDamagedParticles, true)) { log_machine.WriteLine(line); log_machine.Close(); } }
// ------------------------------------------------------------------------------------------------ // ログファイルオープン // ------------------------------------------------------------------------------------------------ // 出力ディレクトリが存在しなければ生成する // 出力ファイルが存在しなければ、生成する // 出力ファイルが存在すれば、追加出力を行う // ログファイル名は、 タスク名称_ログ日付.LOG で出力する // ログオープンフラグ を 1 にする public void OpenLog_Base() { if (LogOpenFlg_Base == 1) { return; } try { FS = null; SW = null; //ログのディレクトリが存在しない場合 if (System.IO.Directory.Exists(LogFolderPath_Base) == false) { //ログディレクトリフォルダ生成 System.IO.Directory.CreateDirectory(LogFolderPath_Base); } //ファイルが存在しない時 if (System.IO.File.Exists(LogFilePath_Base) == false) { //ファイル書き込み用のオブジェクト作成 //この時点で空のログデータができあがる System.IO.StreamWriter SWF = System.IO.File.CreateText(LogFilePath_Base); SWF.Close(); } //ログデータをOpenする FS = System.IO.File.OpenWrite(LogFilePath_Base); // FileStreamとStreamWriterをいっぺんにNEWする SW = new System.IO.StreamWriter(FS); //ログデータの末尾にSeekする SW.BaseStream.Seek(0, System.IO.SeekOrigin.End); LogOpenFlg_Base = 1; } catch (Exception ex) { CloseLog_Base(); throw ex; } }