protected Dispose ( bool disposing ) : void | ||
disposing | bool | |
Результат | void |
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; } }
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(); } } }
private static void Main(string[] args) { StreamReader reader = new StreamReader("../../wordFile.txt"); StreamReader readerSearchFile = new StreamReader("../../textFile.txt"); StreamWriter writer = new StreamWriter("../../resultFile.txt"); try { SortedDictionary<String, int> words = new SortedDictionary<string, int>(); string word = reader.ReadLine(); string textFile = readerSearchFile.ReadToEnd().ToLower(); while (word != null) { word = word.ToLower(); string pattern = @"\b" + word + @"\b"; MatchCollection matches = Regex.Matches(textFile, pattern); words.Add(word, matches.Count); word = reader.ReadLine(); } var ordered = words.OrderByDescending(pair => pair.Value); foreach (KeyValuePair<string, int> pair in ordered) { writer.WriteLine("{0} - {1}", pair.Key, pair.Value); } } finally { writer.Flush(); reader.Dispose(); readerSearchFile.Dispose(); writer.Dispose(); } }
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(); } }
/* sample * */ public static async Task<string> MakePostRequest (string url, string data, string cookie, bool isJson = true) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url); if (isJson) request.ContentType = "application/json"; else request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.Headers ["Cookie"] = cookie; var stream = await request.GetRequestStreamAsync (); using (var writer = new StreamWriter (stream)) { writer.Write (data); writer.Flush (); writer.Dispose (); } var response = await request.GetResponseAsync (); var respStream = response.GetResponseStream(); using (StreamReader sr = new StreamReader (respStream)) { //Need to return this response return sr.ReadToEnd(); } }
/// <summary> /// Writes a line in mLogFile. Line begins with current timestamp, then calling method, finally the passed in msg to log. /// If we don't have a log path specified (it is empty string) we don't log anything. /// </summary> /// <param name="methodName"></param> /// <param name="msg"></param> internal void Log(string methodName, string msg, int levelThisMsg, bool lineSpaceBeforeAndAfter=false) { try { if (string.IsNullOrEmpty(mLogPath)) return; if (mLogLevel < levelThisMsg) return; TimeSpan difference = DateTime.Now - mLastCleanLogTime; // in case this instantiation exits for extended periods of time, we will check each time we log to see if we should do a clean if(difference.TotalHours > 24) { CleanLogFiles(difference.TotalHours); } StreamWriter sw = new StreamWriter(mLogFile, true); DateTime now = DateTime.Now; string time = now.ToString("HH:mm:ss"); if (lineSpaceBeforeAndAfter) sw.WriteLine(""); sw.WriteLine("{0} {1}:{2} - {3}", time, methodName, levelThisMsg, msg); if (lineSpaceBeforeAndAfter) sw.WriteLine(""); sw.Close(); sw.Dispose(); } catch (Exception e) { // } }
/// <summary> /// 日志记录 /// </summary> /// <param name="message">要写入消息</param> /// <param name="path">文件路径:C:\\Log.txt</param> public static void WriteLog(string message, LogFile logFile) { string pathFile = null; switch (logFile) { case LogFile.GetProxyIP: pathFile = "C:\\GreamGugGetProxyIP.txt"; break; case LogFile.SetIE: pathFile = "C:\\GreamGugProxies.txt"; break; case LogFile.ValidateProxy: pathFile = "C:\\GreamGugValidateProxy.txt"; break; default: pathFile = "C:\\GreamGugLog.txt"; break; } try { StreamWriter sw = new StreamWriter(pathFile, true, Encoding.UTF8); sw.WriteLine("{0} ---{1}", DateTime.Now.ToLongDateString(), message); sw.Close(); sw.Dispose(); } catch (IOException ex) { return; } }
static void FileWrite(string contents, int lineNumber) { StreamWriter writeToFile = new StreamWriter("..\\..\\testresult.txt", true, Encoding.GetEncoding("windows-1251")); writeToFile.Write("{0}.", lineNumber); writeToFile.WriteLine(contents); writeToFile.Dispose(); }
private void Write(string fileName, Player player) { string winners = $"{player.name}, {player.won}"; using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(winners); sw.Dispose(); } }
public static void WriteToFile() { if (QueueMessage.Count > 0) { FileStream fs = null; StreamWriter sw = null; try { if (SetupBasePath == null) SetupBasePath = "D:\\"; string FileName = "Log." + DateTime.Now.ToString("yyyyMMddHH") + ".txt"; fs = File.Open(SetupBasePath + FileName, FileMode.Append); sw = new StreamWriter(fs, Encoding.UTF8); while (QueueMessage.Count > 0) { string dq = QueueMessage.Dequeue(); sw.WriteLine(dq); } sw.Close(); fs.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (fs != null) fs.Dispose(); if (sw != null) sw.Dispose(); } } }
//users [LOGIN] public static void Serialize(List<User> iList, string iFileName) { UsersCollection Coll = new UsersCollection(); foreach (User usr in iList) { Coll.uList.Add(usr); } XmlRootAttribute RootAttr = new XmlRootAttribute(); RootAttr.ElementName = "UsersCollection"; RootAttr.IsNullable = true; XmlSerializer Serializer = new XmlSerializer(typeof(UsersCollection), RootAttr); StreamWriter StreamWriter = null; try { StreamWriter = new StreamWriter(iFileName); Serializer.Serialize(StreamWriter, Coll); } catch (Exception Ex) { Console.WriteLine("Exception while writing into DB: " + Ex.Message); } finally { if (null != StreamWriter) { StreamWriter.Dispose(); } } }
public void ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData() { DataTableBuilder builder = new DataTableBuilder(); var stream = new MemoryStream(); var sw = new StreamWriter(stream); var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", }; foreach (var row in rows) { sw.WriteLine(row); } sw.Flush(); stream.Seek(0, SeekOrigin.Begin); try { var lazy = builder.ReadLazy(stream, rows[0].Split(',')); Assert.Equal(rows[0].Split(','), lazy.ColumnNames); var rowEnumerator = rows.Skip(0).GetEnumerator(); rowEnumerator.MoveNext(); var rowCount = 0; foreach (var row in lazy.Rows) { Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values)); rowEnumerator.MoveNext(); rowCount++; } Assert.Equal(rows.Length, rowCount); } finally { sw.Dispose(); stream.Dispose(); } }
private void okBtn_Click(object sender, EventArgs e) { try { File.Delete(setup.viewprefs); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(setup.viewprefs)) { if (explorerBox.Checked == true) sw.WriteLine("true"); else sw.WriteLine("false"); if (statusBox.Checked == true) sw.WriteLine("true"); else sw.WriteLine("false"); if (debuggingBox.Checked == true) sw.WriteLine("true"); else sw.WriteLine("false"); if (lnBox.Checked) sw.WriteLine("true"); else sw.WriteLine("false"); sw.Dispose(); } } catch { MessageBox.Show("Could not save preferences.\nDefault values have been saved instead.", "Scale", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } this.Close(); }
public override void Close() { StringBuilder sb = new StringBuilder(); ResolveResponseScripts(sb); string responseText = sb.ToString(); // 文件上传,此时应该对返回的数据进行编码,因为ExtJs会将返回的数据放在<pre></pre>中,导致自定编码 if (HttpContext.Current.Request.ContentType.Contains("multipart/form-data")) { // HttpUtility.UrlEncode 在 Encode 的时候, 将空格转换成加号,而客户端的 encodeURIComponent 则是将空格转换为 %20 responseText = HttpUtility.UrlEncode(responseText); responseText = responseText.Replace("+", "%20"); } // 从输出流创建TextWriter TextWriter writer = new StreamWriter(_responseStream, Encoding.UTF8); writer.Write(responseText); // 输出 writer.Flush(); writer.Dispose(); base.Close(); _responseStream.Close(); }
/// <summary> /// Questo metodo viene usato per identificare e registrare il dispositivo nel database /// </summary> /// <param name="id">Identificativo del dispositivo</param> /// <returns></returns> public bool Setup(string id, bool owner = false) { Id = id; var table = Database.LiteDatabase.singleton.GetTable("devices"); if (table != null) { Database.Tables.Devices devices = table as Database.Tables.Devices; var result = devices.Insert("Insert into devices (id, name, owner) VALUES ( NULL, '" + id + "', '" + ((owner)?"1":"0") + "')"); if (result) { if(owner) { StreamWriter wr = new StreamWriter(Filename); wr.WriteLine("DeviceId:" + id); wr.Close(); wr.Dispose(); File.SetAttributes(Filename, FileAttributes.Hidden); } return true; } } return false; }
/// <summary> /// �ڱ���д�������־ /// </summary> /// <param name="exception"></param> public static void WriteLog(string debugstr) { lock (writeFile) { FileStream fs = null; StreamWriter sw = null; try { string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; //����������־Ŀ¼ string folder = HttpContext.Current.Server.MapPath("~/Log"); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); fs = new FileStream(folder + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write); sw = new StreamWriter(fs, Encoding.UTF8); sw.WriteLine( DateTime.Now.ToString() + " " + debugstr + "\r\n"); } finally { if (sw != null) { sw.Flush(); sw.Dispose(); sw = null; } if (fs != null) { // fs.Flush(); fs.Dispose(); fs = null; } } } }
public static void writeObey(string obeyFile, string imgName, string imgSize, string imgMaxSize, string inFolder) { if ( File.Exists( obeyFile ) ) File.Delete( obeyFile ); try { FileStream fileStream = new FileStream( obeyFile, FileMode.Create ); StreamWriter writer = new StreamWriter( fileStream ); writer.WriteLine( "rofsname=" + imgName ); if ( imgSize != "" ) writer.WriteLine( "romsize=" + imgSize ); if ( imgMaxSize != "" ) writer.WriteLine( "rofssize=" + imgMaxSize ); //DirectoryInfo dir = new DirectoryInfo(inFolder); ListBuilder( inFolder, ref fileList ); foreach ( string fn in fileList ) { StringBuilder sb = new StringBuilder( "data=" ); sb.Append( '"' ).Append( fn ).Append( '"' ).Append( " " ).Append( '"' ).Append( Regex.Replace( fn, @"^[a-z]:\\.+\\rofs[123]", "", RegexOptions.IgnoreCase ) ).Append( '"' ); writer.WriteLine( sb.ToString() ); } writer.WriteLine( "rem This OBEY file was created by S60.Lib.Firmware by fonix232 and jandras" ); writer.Dispose(); } catch { } }
public static void Create(string path, string content) { FileStream fs = null; StreamWriter sw = null; try { fs = File.Create(path); sw = new StreamWriter(fs); sw.Write(content); sw.Flush(); } catch (Exception ex) { throw ex; } finally { if (sw != null) { sw.Dispose(); } if (fs != null) { fs.Dispose(); } } }
public static void Save( Player p ) { StreamWriter sw = new StreamWriter( File.Create( "players/" + p.name + "DB.txt" ) ); sw.WriteLine ("Nick = " + p.DisplayName ); sw.Flush(); sw.Close(); sw.Dispose(); }
/// <summary> /// Load a Language using the project resources, depending on the settings. /// </summary> internal void LoadLanguage() { XmlSerializer serializer = new XmlSerializer(_currentLanguage.GetType()); using (MemoryStream stream = new MemoryStream()) { StreamWriter writer = new StreamWriter(stream); string res; switch (Properties.Settings.Default.Language) { case 0: res = Properties.Resources.nl; break; case 1: res = Properties.Resources.eng; break; case 2: res = Properties.Resources.ita; break; case 3: res = Properties.Resources.pl; break; case 4: res = Properties.Resources.tr; break; default: res = Properties.Resources.eng; break; } writer.Write(res); writer.Flush(); stream.Position = 0; _currentLanguage = (Language)serializer.Deserialize(stream); writer.Dispose(); } }
/// <summary> /// Metoda za digitalno potpisivanje dokumenta /// </summary> /// <param name="file"></param> public void MakeDigitalSignature(string file) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader streamReader = new StreamReader("privatni_kljuc.txt"); string publicOnlyKeyXml = streamReader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXml); streamReader.Close(); streamReader.Dispose(); FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read); BinaryReader binReader = new BinaryReader(dat); byte[] data = binReader.ReadBytes((int)dat.Length); byte[] sign = rsa.SignData(data, "SHA1"); binReader.Close(); binReader.Dispose(); dat.Close(); dat.Dispose(); string datName = file + ".dp"; TextWriter tw = new StreamWriter(datName); tw.WriteLine(Convert.ToBase64String(sign)); tw.Close(); tw.Dispose(); }
/// <summary> /// Writes entries to the data file /// </summary> /// <param name="employeeList">List of employee objects to be written</param> public void WriteToFile(List<Employee> employeeList) { StreamWriter writer = null; try { writer = new StreamWriter(fileName); writer.Write(JsonConvert.SerializeObject(employeeList)); } catch (JsonSerializationException) { throw new JsonSerializationException(); } catch (IOException) { throw new IOException(); } catch(NotSupportedException) { throw new NotSupportedException(); } finally { if (writer != null) writer.Dispose(); } }
public void OnLoad(string[] args) { Player.OnAllPlayersChat.Normal += OnChat6; Player.OnAllPlayersConnect.Normal += OnConnect6; Player.OnAllPlayersCommand.Normal += OnCommand6; if (!Directory.Exists("logs/Separate")) Directory.CreateDirectory("logs/Separate"); if (!File.Exists("SeparateLogging.config")) using (StreamWriter w = new StreamWriter(File.Create("SeparateLogging.config"))) { w.WriteLine("### The line below this determines whether everyone is logged separately, or whether only select players will be logged separately. Valid options are all or select. ###"); w.WriteLine("all"); w.WriteLine("### Put the name(s) of the player(s) you want to log separately below. (Not case sensitive.) ###"); w.WriteLine("Notch"); w.WriteLine("Herobrine"); w.Close(); w.Dispose(); } string[] lines = File.ReadAllLines("SeparateLogging.config"); all = lines[1] == "all"; if (!all) foreach (string l in lines) if (l != "all" && !l.StartsWith("#") && !l.StartsWith(" ")) players.Add(l.ToLower()); if (all) players = null; }
public void CreateHtml(string temPath, Maticsoft.Model.CMS.Content model, string createPath) { string str = string.Empty; string str2 = string.Empty; try { str2 = HttpContext.Current.Server.MapPath(createPath); StreamReader reader = new StreamReader(System.IO.File.Open(HttpContext.Current.Server.MapPath(temPath), FileMode.Open, FileAccess.Read), Encoding.GetEncoding("utf-8")); StringBuilder builder = new StringBuilder(reader.ReadToEnd()); reader.Close(); reader.Dispose(); string str4 = builder.ToString().Replace("$id$", model.ContentID.ToString()).Replace("$content$", model.Description); this.CreatFolder(createPath); str = "ContentDetail-" + model.ContentID + ".html"; StreamWriter writer = new StreamWriter(System.IO.File.Create(str2 + "/" + str), Encoding.GetEncoding("utf-8")); writer.Write(str4); writer.Flush(); writer.Close(); writer.Dispose(); } catch (Exception) { throw; } }
public void Post(UserSocialConnection ConnectionData, string Update) { try { string apiCallUrl = String.Format("https://graph.facebook.com/me/feed"); // Format the call string HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(apiCallUrl); wr.Method = "POST"; wr.ContentType = "application/x-www-form-urlencoded"; string data = "access_token=" + ConnectionData.Token + "&message=" + HttpUtility.UrlEncode(Update); wr.ContentLength = data.Length; StreamWriter sw = new StreamWriter(wr.GetRequestStream()); sw.Write(data); sw.Close(); StreamReader sr = new StreamReader(wr.GetResponse().GetResponseStream()); string jsonResponse = sr.ReadToEnd(); sr.Close(); sw.Dispose(); sr.Dispose(); if (jsonResponse.Contains("\"error_code\"")) // Proces the response for errors - a simple throw is used to convert the text error in to an exception throw new Exception(String.Format("Error calling facebook API!\nJSON: {0} \nAPI CALL: {1}", jsonResponse, apiCallUrl)); } catch (Exception ex) { Debug.WriteLine("Exception occurred in FacebookSocialConnector.Post processing User ID #" + ConnectionData.UserId + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } }
protected void btn_submit_Click(object sender, EventArgs e) { StreamWriter sw = null; try { if (File.Exists(filepath)) { File.Delete(filepath); } sw = new StreamWriter(filepath, false); sw.Write(txt_term.Text.Trim()); // Write the file. Page.ClientScript.RegisterClientScriptBlock(GetType(), "PopupScript", "<script>alert('Change succeeded!');window.location.href='terms-conditions.aspx';</script>"); } catch (Exception ex) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "PopupScript", "<script>alert('" + ex.Message + "');</script>"); } finally { if (sw != null) { //sw.Flush(); sw.Close(); // Close the instance of StreamWriter. sw.Dispose(); // Dispose from memory. } } }
public static void WriteLog(string text) { if (!Directory.Exists(ConfigurationManager.AppSettings["logPath"])) { Directory.CreateDirectory(ConfigurationManager.AppSettings["logPath"]); } string filename = ConfigurationManager.AppSettings["logPath"] + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; lock (lockk) { using (var fs = new FileStream(filename, FileMode.Append)) { using (var sw = new StreamWriter(fs)) { if (!string.IsNullOrEmpty(text)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + text); } else { sw.WriteLine(text); } sw.Close(); sw.Dispose(); } } } }
public static void Debug(object message) { StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath + "\\log.txt", true, System.Text.Encoding.UTF8); sw.Write(message.ToString()); sw.Close(); sw.Dispose(); }
public void OutOptionsTest() { MemoryStream memStream = new MemoryStream(); StreamWriter writer = new StreamWriter(memStream); writer.AutoFlush = true; InstallerLog.AddWriter(writer, InstallerLog.DefaultLineFormat); String line = "test"; InstallerLog.WriteLine(line); memStream.Position = 0; StreamReader reader = new StreamReader(memStream); Assert.AreEqual(line, reader.ReadLine(), "DefaultLineFormat should only write the line itself."); memStream.Position = 0; InstallerLog.RemoveWriter(writer, false); InstallerLog.AddWriter(writer, InstallerLog.TimeStampedLineFormat); InstallerLog.WriteLine(line); memStream.Position = 0; String expectedLine = String.Format(InstallerLog.TimeStampedLineFormat, line, DateTime.Now.ToString()); Assert.AreEqual(expectedLine, reader.ReadLine(), "TimeStampLineFormat should include timestamp."); writer.Dispose(); reader.Dispose(); }
public static void log_write(string str, string reason, string logname) { string EntryTime = DateTime.Now.ToLongTimeString(); string EntryDate = DateTime.Today.ToShortDateString(); string fileName = "log/" + logname + ".log"; //log + data +logname ? if (!Directory.Exists(Environment.CurrentDirectory + "/log/")) { Directory.CreateDirectory((Environment.CurrentDirectory + "/log/")); } try { StreamWriter sw = new StreamWriter(fileName, true, System.Text.Encoding.UTF8); sw.WriteLine("[" + EntryDate + "][" + EntryTime + "][" + reason + "]" + " " + str); sw.Close(); //check this sw.Dispose(); } catch (Exception ex) { log_write(ex.Message, "Exception", "Exception"); MessageBox.Show(ex.Message); } }
protected virtual void Dispose(bool disposing) { #if !UNITY_FLASH if (!this.m_disposed) { if (disposing && m_file != null) { m_file.Dispose(); } m_disposed = true; } #endif }
public static void writeSpecLog(string ps_text, string ps_path) { if (LOG_IND == 1) { if (!System.IO.Directory.Exists(ps_path.Substring(0, ps_path.LastIndexOf("\\")))) { System.IO.Directory.CreateDirectory(ps_path.Substring(0, ps_path.LastIndexOf("\\"))); } System.IO.StreamWriter file = new System.IO.StreamWriter(ps_path, true, System.Text.Encoding.UTF8); file.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + ps_text); file.Close(); file.Dispose(); file = null; } }
/// <summary> /// Cleans up resources /// </summary> public void Dispose() { if (!_disposed) { if (Connected) { Disconnect(); } irclog.Close(); irclog.Dispose(); _outgoingStream?.Dispose(); _ircTcpClient?.Close(); _ircTcpClient?.Dispose(); _disposed = true; } }
public static void log(string Message) { string Path, FileName; string Msg = string.Empty; Msg += DateTime.Now.ToString(); Msg += " " + Message; FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName + DateTime.Now.ToString("yyyyMMdd") + ".log"; Path = "C:\\Log\\" + FileName; System.IO.Directory.CreateDirectory("C:\\Log\\"); System.IO.StreamWriter sw = new System.IO.StreamWriter(Path, true, System.Text.Encoding.GetEncoding("big5")); sw.WriteLine(Msg); sw.WriteLine(""); sw.Dispose(); sw = null; }
public static void CreateTextAsset() { string path = AssetDatabase.GetAssetPath(Selection.activeInstanceID); if (!AssetDatabase.Contains(Selection.activeInstanceID)) path = "Assets"; if (!System.IO.Directory.Exists(path)) path = System.IO.Path.GetDirectoryName(path); path = System.IO.Path.Combine(path, "New Text.txt"); path = AssetDatabase.GenerateUniqueAssetPath(path); System.IO.StreamWriter writer = System.IO.File.CreateText(path); writer.Close(); writer.Dispose(); AssetDatabase.ImportAsset(path); Selection.activeObject = AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)); }
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.UTF8); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } }
public static void Write(string logContentr, string filename) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath("log/" + filename + ".txt"), true)) { StringBuilder str = new StringBuilder(); str.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ")); str.Append("\r\n"); str.Append(Utils.getUserIP()); str.Append("\r\n"); str.Append(logContentr); str.Append("\r\n"); str.Append("------------------------------------------------------------------------"); sw.WriteLine(Convert.ToString(str)); sw.Close(); sw.Dispose(); } }
/// <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 {} }
//بدنه متد نوشتن در فایل های پروژه #region WriteToFiles_Write(string pathName, string text, bool append) /// <summary> /// متد رایت که یک مسیر و یک متن و یک بولین اپند میگیره /// </summary> /// <param name="pathName"></param> /// <param name="text"></param> /// <param name="append"></param> public static void Write(string pathName, string text, bool append) { //اگر مسیر نال باشه از متد خارج میشود if (pathName == null) { return; } //رشته حاوی مسیر تریم میشود pathName = pathName.Trim(); //اگر امپتی شد از متد خارج میشود if (pathName == string.Empty) { return; } //پارامتر دوم متد که یک متن هست اگر نال بود برابر با امپتی میشود if (text == null) { text = string.Empty; } //از استریم رایتر استفاده کردیم System.IO.StreamWriter oStream = null; try { //نیو شدن استریم رایتر با پارامتر اول و سوم متد جاری oStream = new System.IO.StreamWriter(pathName, append, System.Text.Encoding.UTF8); //نوشتن در متن که پرامتر دوم متد جاری است oStream.Write(text); } //بستن شی استریم رایتر finally { if (oStream != null) { oStream.Close(); oStream.Dispose(); oStream = null; } } }
public static void UpdateFilePadding(string file, int nodeId, int padding) //Update node paddings { byte[] inFile = System.IO.File.ReadAllBytes(file); int nodeCount = GetFileNodeCount(file); int pos; uint tempNodeStartPos; uint tempNodeEndPos; uint dataStartPos = Makeu32(inFile[0x0C], inFile[0x0D], inFile[0x0E], inFile[0x0F], IsLittleEndian(file)); uint[] nodePaddings = new uint[nodeCount]; nodePaddings = GetFileNodePaddings(file); int calculatedPadding = (int)nodePaddings[nodeId] + padding; pos = 0x28 + (0x10 * nodeId); //get position of the node pos += 4; //line of node's end data position uint breakPoint = Makeu32(inFile[pos], inFile[pos + 1], inFile[pos + 2], inFile[pos + 3], IsLittleEndian(file)) + dataStartPos; //find break point to split and rebuild byte[] startDataBuild = new byte[breakPoint + calculatedPadding]; byte[] endDataBuild = new byte[inFile.Length - (breakPoint + nodePaddings[nodeId])]; Array.Copy(inFile, startDataBuild, breakPoint); //copy before changed padding Array.Copy(inFile, (breakPoint + nodePaddings[nodeId]), endDataBuild, 0, inFile.Length - (breakPoint + nodePaddings[nodeId])); //copy after changed padding pos += 0x10 - 4; //next node line at start pos for (int i = nodeId + 1; i < nodeCount; i++) //change the nodes below it { tempNodeStartPos = (uint)((Makeu32(inFile[pos], inFile[pos + 1], inFile[pos + 2], inFile[pos + 3], IsLittleEndian(file))) + padding); for (int j = pos; j < (pos + 4); j++) { startDataBuild[j] = Breaku32(tempNodeStartPos, IsLittleEndian(file))[j - pos]; //Update calculation of new node data Start position } pos += 4; tempNodeEndPos = (uint)((Makeu32(inFile[pos], inFile[pos + 1], inFile[pos + 2], inFile[pos + 3], IsLittleEndian(file))) + padding); for (int j = pos; j < (pos + 4); j++) { startDataBuild[j] = Breaku32(tempNodeEndPos, IsLittleEndian(file))[j - pos]; //Update calculation of new node data End position } pos += 0x10 - 4; } System.IO.StreamWriter stream = new System.IO.StreamWriter(file); stream.BaseStream.Write(startDataBuild, 0, startDataBuild.Length); stream.BaseStream.Write(endDataBuild, 0, endDataBuild.Length); stream.Close(); //Save stream.Dispose(); //End stream }
private void setGuestLogoToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog fbd = new OpenFileDialog(); string sSelectedFile = ""; if (fbd.ShowDialog() == DialogResult.OK) { sSelectedFile = fbd.FileName; guestlogopath = sSelectedFile; System.IO.StreamWriter writer = new System.IO.StreamWriter("c:/temp/guestpfad.txt"); writer.Write(sSelectedFile); writer.Close(); writer.Dispose(); FileStream imageStreamGuest = new FileStream(guestlogopath, FileMode.Open, FileAccess.Read); scb.pBGuest.Image = System.Drawing.Image.FromStream(imageStreamGuest); } }
/**************************************** * 函数名称:WriteFile * 功能说明:当文件不存时,则创建文件,并追加文件 * 参 数:Path:文件路径,Strings:文本内容 * 调用示列: * string Path = Server.MapPath("Default2.aspx"); * string Strings = "这是我写的内容啊"; * Common.Utility.FileOperate.WriteFile(Path,Strings); *****************************************/ /// <summary> /// 写文件 /// </summary> /// <param name="Path">文件路径</param> /// <param name="Strings">文件内容</param> public static void WriteFile(string Path, string Strings, string encode = "") { Encoding code = Encoding.Default; if (string.IsNullOrWhiteSpace(encode)) { code = Encoding.GetEncoding(encode); } if (!System.IO.File.Exists(Path)) { System.IO.FileStream f = System.IO.File.Create(Path); f.Close(); f.Dispose(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, code); f2.WriteLine(Strings); f2.Close(); f2.Dispose(); }
static void Main(string[] args) { // read the data file and write to the output every 150 ms until the user hits Enter key while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)) { DateTime startDateTime = DateTime.Now; DateTime endDateTime = DateTime.Now; int counter = 0; string line = ""; int sum = 0; System.IO.StreamReader file = new System.IO.StreamReader("data"); System.IO.StreamWriter output = new System.IO.StreamWriter("output"); // Continuously read the file line by line. while ((line = file.ReadLine()) != null && (endDateTime - startDateTime).Milliseconds < 150) { Int16 value = Convert.ToInt16(line); sum += value; counter++; endDateTime = DateTime.Now; } output.WriteLine("sum of {0} lines read in {1} milliseconds = {2}", counter, (endDateTime - startDateTime).Milliseconds, sum); output.Close(); output.Dispose(); // Rename the output.txt file. if (File.Exists("outputOld")) { File.Delete("outputOld"); } File.Move("output", "outputOld"); file.Close(); file.Dispose(); System.Console.WriteLine("sum of {0} lines read in {1} milliseconds = {2}", counter, (endDateTime - startDateTime).Milliseconds, sum); sum = 0; } }
/// <summary> /// 写文件 /// </summary> /// <param name="Path">文件路径</param> /// <param name="Strings">文件内容</param> public static void WriteNewFile(string Path, string Strings) { try { if (!System.IO.File.Exists(Path)) { System.IO.FileStream f = System.IO.File.Create(Path); f.Close(); f.Dispose(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, System.Text.Encoding.UTF8); f2.WriteLine(Strings); f2.Close(); f2.Dispose(); } catch { } }
/// <summary> /// 写文件,会覆盖掉以前的内容 /// </summary> /// <param name="Path">文件路径</param> /// <param name="Strings">文件内容</param> /// <example> /// string Path = Server.MapPath("Default2.aspx"); /// string Strings = "没是测试内容。"; /// FileHelper.WriteFile(Path,Strings); /// </example> public static void WriteFile(string Path, string Strings) { if (!System.IO.File.Exists(Path)) { string directoryPath = Path.Substring(0, Path.LastIndexOf("\\")); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } System.IO.FileStream f = System.IO.File.Create(Path); f.Close(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312")); f2.Write(Strings); f2.Close(); f2.Dispose(); }
private void ExportLog() { string now = DateTime.Now.ToString("dd.MM.yyyy-hh-mm-ss"); SaveFileDialog s = new SaveFileDialog(); s.Title = "Save log file"; s.FileName = now + "-xxUSBSentinel.log"; s.Filter = "Text files (*.txt)|*.txt|Log files (*.log)|*.log|All files (*.*)|*.*"; if (s.ShowDialog() == DialogResult.OK) { System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(s.OpenFile()); foreach (var item in ListBox1.Items) { SaveFile.WriteLine(item.ToString()); } MessageBox.Show("Saved!"); SaveFile.Dispose(); } }
public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } }
//************************************************************************************* //NOMBRE DE LA FUNCIÓN: Btn_Migrar_Click //DESCRIPCIÓN: Evento Click del botón migrar para comenzar a leer el archivo y guardar los datos // en la base de datos //PARÁMETROS : //CREO : Miguel Angel Bedolla Moreno //FECHA_CREO : 22-Febrero-2013 //MODIFICO: //FECHA_MODIFICO //CAUSA_MODIFICACIÓN //************************************************************************************* private void Btn_Migrar_Click(object sender, EventArgs e) { if (Txt_Ruta.Text.Trim() != "") { if (Txt_Ruta.Text.EndsWith(".xlsx") || Txt_Ruta.Text.EndsWith(".xls")) { try { //DataSet Ds_Archivo = Leer_Excel("SELECT * FROM [Tipo_de_contenedor$] where [Proyecto] <>''"); DataSet Ds_Archivo = Interpretar_Excel(); Cls_Ope_Migracion_Negocio P_Migracion = new Cls_Ope_Migracion_Negocio(); P_Migracion.P_Dt_Contenedores = Ds_Archivo.Tables["Contenedores"]; P_Migracion.P_Dt_Tipo_Contenedores = Ds_Archivo.Tables["Tipo_de_Contenedor"]; if (P_Migracion.Alta_Migracion()) { if (P_Migracion.P_Log_Errores.Trim() != "") { MessageBox.Show(this, "Migración exitosa con comentarios.", "Migración de contenedores", MessageBoxButtons.OK); String Path = @"C:\Log_Errores\Log_" + DateTime.Now.ToString("dd-MMM-yyyy_hh_mm_ss_tt") + ".txt"; if (!Directory.Exists(@"C:\Log_Errores\")) { Directory.CreateDirectory(@"C:\Log_Errores\"); } System.IO.StreamWriter escritor = new System.IO.StreamWriter(Path); escritor.WriteLine(P_Migracion.P_Log_Errores); escritor.Dispose(); MessageBox.Show(this, "Los comentarios se guiardaron en el archivo: " + Path + ".", "Migración de contenedores", MessageBoxButtons.OK); } else { MessageBox.Show(this, "Migración exitosa.", "Migración de contenedores", MessageBoxButtons.OK); } } } catch (Exception E) { MessageBox.Show(this, "Migración fallida: " + E.Message, "Migración de contenedores", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
private void WriteDataToFile() { print("Saving volume data...."); saveToFile = false; int i = 0; StreamWriter writer = new System.IO.StreamWriter(filepath, false, Encoding.UTF8); writer.Write(kinectSettings.Serialized + KinectUtilities.configBreak); foreach (string frame in base64Frames) { if (frame != null && frame != "") { i++; writer.Write(frame + KinectUtilities.frameBreak); } } writer.Close(); writer.Dispose(); print(i + " frames of volume data have been saved to " + filepath); }
public static void log(string @message1, string @message2) { string @message = @message1 + @message2; try { if (@message == null) { throw new ArgumentNullException("string"); } string currentTime = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(); var objFile = new System.IO.StreamWriter( System.AppDomain.CurrentDomain.BaseDirectory + @"\botlogs.txt", true); objFile.WriteLine("(" + currentTime + ") " + @message); objFile.Close(); objFile.Dispose(); } catch (Exception e) { Console.WriteLine("Exception: " + e); } }
/// <summary> /// 写文件,如果文件不存在则创建,存在则追加 /// </summary> /// <param name="path">文件路径</param> /// <param name="strings">内容</param> /// <param name="encod">编码,默认utf-8</param> public static void WriteFile2(string path, string strings, string encod = "utf-8") { path = FilePathProcess(path); string dir = System.IO.Path.GetDirectoryName(path); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } if (!System.IO.File.Exists(path)) { System.IO.FileStream f = System.IO.File.Create(path); f.Close(); f.Dispose(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.GetEncoding(encod)); f2.Write(strings); f2.Close(); f2.Dispose(); }
/**************************************** * 函数名称:WriteFile * 功能说明:当文件不存时,则创建文件,并追加文件 * 参 数:Path:文件路径,Strings:文本内容 * 调用示列: * string Path = Server.MapPath("Default2.aspx"); * string Strings = "这是我写的内容啊"; * EC.FileObj.WriteFile(Path,Strings); *****************************************/ /// <summary> /// 写文件 /// </summary> /// <param name="Path">文件路径</param> /// <param name="Strings">文件内容</param> public static void WriteFile(string Path, string Strings) { if (System.IO.File.Exists(Path)) { System.IO.File.Delete(Path); } if (!System.IO.File.Exists(Path)) { //Directory.CreateDirectory(Path); System.IO.FileStream f = System.IO.File.Create(Path); f.Close(); f.Dispose(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8); f2.WriteLine(Strings); f2.Close(); f2.Dispose(); }
private static void WriteError(string message) { try { lock (lockerError) { Init(); string fileName = string.Empty; fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Logs\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + String.Format("Error-{0:yyyyMMdd}", DateTime.Now) + ".txt"; using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true)) { sw.Write(String.Format("{0:dd/MM/yyyy-HH:mm:ss} | ", DateTime.Now)); sw.WriteLine(message); sw.Close(); sw.Dispose(); } //try //{ // string email = System.Configuration.ConfigurationManager.AppSettings["ErrorReportEmail"]; // if (!string.IsNullOrEmpty(email)) // { // using (var db = new DataEntities()) // { // var conf = db.SettingEmail.FirstOrDefault(); // if (conf != null) // { // conf.EmailTo = email; // Shared.SendEmail(conf, "เกิดข้อผิดพลาด","["+ DateTime.Now.ToString("dd/MM/yyyy HH:mm") +"] " + message); // } // } // } //}catch{} } } catch { } }
protected void Page_Load(object sender, System.EventArgs e) { if (!this.Page.IsPostBack) { this.BindSiteMap(); } string text = HiContext.Current.HostPath + Globals.ApplicationPath + "/sitemapindex.xml"; this.Hysitemap.Text = text; this.Hysitemap.NavigateUrl = text; this.Hysitemap.Target = "_blank"; System.IO.StreamReader streamReader = new System.IO.StreamReader(base.Server.MapPath(Globals.ApplicationPath + "/robots.txt"), System.Text.Encoding.Default); string text2 = streamReader.ReadToEnd(); streamReader.Close(); if (text2.Contains("Sitemap")) { text2 = text2.Substring(0, text2.IndexOf("Sitemap")); } System.IO.FileStream fileStream = new System.IO.FileStream(base.Server.MapPath(Globals.ApplicationPath + "/robots.txt"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); try { using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream, System.Text.Encoding.Default)) { streamWriter.Flush(); streamWriter.Write(text2); streamWriter.WriteLine("Sitemap: " + text); streamWriter.Flush(); streamWriter.Dispose(); streamWriter.Close(); } } catch (System.Exception) { } finally { fileStream.Dispose(); fileStream.Close(); } }
/// <summary> /// 另保存文件,文件存在则覆盖,注释的key为# /// </summary> /// <param name="filePath">要保存的文件的路径</param> public void SaveAs(string filePath) { filePath = FileHelper.FilePathProcess(filePath); if (File.Exists(filePath)) //文件存在则删除 { System.IO.StreamWriter sw1 = new System.IO.StreamWriter(filePath, false); sw1.Write(""); sw1.Close(); sw1.Dispose(); } //创建文件 string dir = System.IO.Path.GetDirectoryName(filePath); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } if (!System.IO.File.Exists(filePath)) { System.IO.FileStream f = System.IO.File.Create(filePath); f.Close(); f.Dispose(); } System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true); foreach (object item in _keylist) { String key = (String)item; String val = (String)this[key]; if (key.StartsWith("#")) { sw.WriteLine(key + val); } else { sw.WriteLine(key + "=" + val); } } sw.Close(); sw.Dispose(); }
private void setFontColorToolStripMenuItem_Click(object sender, EventArgs e) { ColorDialog MyDialog = new ColorDialog(); MyDialog.ShowDialog(); // Keeps the user from selecting a custom color. MyDialog.AllowFullOpen = false; // Allows the user to get help. (The default is false.) MyDialog.ShowHelp = true; // Sets the initial color select to the current text color. scb.lbTextDown.ForeColor = MyDialog.Color; scb.lbTextQuarter.ForeColor = MyDialog.Color; scb.lbTime.ForeColor = MyDialog.Color; scb.lbTextHome.ForeColor = MyDialog.Color; scb.lbTextGuest.ForeColor = MyDialog.Color; scb.lbTitle.ForeColor = MyDialog.Color; System.IO.StreamWriter writer = new System.IO.StreamWriter("c:/temp/fontcolor.txt"); writer.Write(MyDialog.Color.Name); writer.Close(); writer.Dispose(); }
public static void CreateGestureFile(string gestureName, string networkName) { string gestureFileLocation = Application.streamingAssetsPath + Config.NEURAL_NET_PATH + networkName + "/Gestures/"; // if no gestures folder already if (!System.IO.Directory.Exists(gestureFileLocation)) { // create gestures folder System.IO.Directory.CreateDirectory(gestureFileLocation); } // create the gesture file string fullPath = gestureFileLocation + gestureName + ".txt"; System.IO.StreamWriter file = new System.IO.StreamWriter(fullPath, true); file.Dispose(); #if UNITY_EDITOR AssetDatabase.ImportAsset(fullPath); #endif }
/// <summary> /// 保存数据data到文件 /// </summary> /// <param name="text">数据</param> /// <param name="fileName">文件名</param> /// <returns>保存的文件全路径</returns> public static String saveFile(String text, String fileName) { string CurDir = System.AppDomain.CurrentDomain.BaseDirectory; if (!System.IO.Directory.Exists(CurDir)) { System.IO.Directory.CreateDirectory(CurDir); } String filePath = CurDir + fileName; //文件以覆盖方式添加内容 System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false); //保存数据到文件 file1.Write(text); file1.Close(); file1.Dispose(); return(filePath); }
private static void WriteAdjacencyMatrix(int[,] Matrix, string DataFilePath) { StreamWriter file = new System.IO.StreamWriter(DataFilePath); for (int i = 0; i <= Matrix.GetUpperBound(0); i++) { string Text = ""; for (int j = 0; j <= Matrix.GetUpperBound(1); j++) { Text += Matrix[i, j].ToString(); if (j != Matrix.GetUpperBound(1)) { Text += " "; } } file.WriteLine(Text); } Matrix = null; file.Close(); file.Dispose(); }
private static void WriteMore(string message, string folderName, string fileName) { try { lock (lockerInfo) { Init(folderName); fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + folderName + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + fileName + ".txt"; using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true)) { sw.Write(String.Format("{0:dd/MM/yyyy-HH:mm:ss} | ", DateTime.Now)); sw.WriteLine(message); sw.Close(); sw.Dispose(); } } } catch { } }