C#读写txt文件的方法
1.添加命名空间
System.IO;
System.Text;
2.文件的读取
#region 读取TXT文本文件 /// <summary> /// FileStream读取文本文件 /// </summary> public void FileStreamRead() { //文件路径 string filePath = AppDomain.CurrentDomain.BaseDirectory; // Server.MapPath("~/UploadFiles/"); //文件夹不存在则创建 if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Today.ToString("yyyMMdd") + ".txt"; if (System.IO.File.Exists(filePath)) { //1.直接读取出字符串 string strText = System.IO.File.ReadAllText(filePath); //2.按行读取为字符串数组 string[] arrFileText = System.IO.File.ReadAllLines(filePath); //3.FileStream读取写入给定的缓存区 System.IO.FileStream fs = new FileStream(filePath, FileMode.Open); fs.Seek(0, SeekOrigin.Begin); byte[] byData = new byte[100]; fs.Read(byData, 0, 100);//byData传进来的字节数组,用以接受FileStream对象中的数据 System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder(); char[] charData = new char[1000]; d.GetChars(byData, 0, byData.Length, charData, 0); fs.Close(); } } /// <summary> /// StreamReader读取文本文件 /// </summary> public void StreamReaderRead() { //文件路径 string filePath = AppDomain.CurrentDomain.BaseDirectory; // Server.MapPath("~/UploadFiles/"); //文件夹不存在则创建 if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Today.ToString("yyyMMdd") + ".txt"; if (System.IO.File.Exists(filePath)) { //1.从头到尾以流的方式读出文本文件,该方法会读出一行文本 System.IO.StreamReader sr = new StreamReader(filePath); string strStreamReader = sr.ReadToEnd(); sr.Close(); } } #endregion
FileStream fs = new FileStream(@"c:\temp\ascii.txt", FileMode.Open, FileAccess.Read, FileShare.Read); //StreamReader sr3 = new StreamReader(fs); //string str3 = sr3.ReadToEnd(); //sr3.Close(); StreamReader sr4 = new StreamReader(fs, System.Text.Encoding.Default); string strCH = sr4.ReadToEnd(); sr4.Close(); string str2 = System.IO.File.ReadAllText(@"c:\temp\ascii.txt", System.Text.Encoding.ASCII);
3.文件的写入
#region 写入TXT文本文件 /// <summary> /// StreamWriter写入文本文件 /// </summary> public void StreamWriterWrite() { //文件路径 string filePath = AppDomain.CurrentDomain.BaseDirectory; // Server.MapPath("~/UploadFiles/"); //文件不存在则创建 if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Today.ToString("yyyMMdd") + ".txt"; #region 另一种方式 ////FileMode.Append,FileAccess.Write追加文件 //FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate); //StreamWriter sw = new StreamWriter(fs); #endregion StreamWriter sw = new StreamWriter(filePath, true); //Write直接追加文件末尾,不换行;WriteLine直接追加文件末尾,换行 sw.WriteLine("测试StreamWriter写入TXT文件" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); //清空缓冲区、关闭流 sw.Flush(); sw.Close(); //直接追加到文件 //using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath)) //{ // sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); //} } /// <summary> /// FileStream写入文本文件 /// </summary> public void FileStreamWrite() { //文件路径 string filePath = AppDomain.CurrentDomain.BaseDirectory; // Server.MapPath("~/UploadFiles/"); //文件不存在则创建 if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Today.ToString("yyyMMdd") + ".txt"; //1.该方法写入字符数组换行显示 string[] arrFile = { "first line", "second line", "third line", "第四行" }; System.IO.File.AppendAllLines(filePath, arrFile, System.Text.Encoding.Default); //2.字符串写入文本 string strTest = "该例子测试一个字符串写入文本文件。"; System.IO.File.AppendAllText(filePath, strTest, System.Text.Encoding.Default); //3.FileMode.Append,FileAccess.Write追加文件 FileStream fs = new FileStream(filePath, FileMode.Append,FileAccess.Write); byte[] data = System.Text.Encoding.Default.GetBytes("测试FileStream写入TXT文件" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); fs.Write(data, 0, data.Length); //清空缓冲区、关闭流 fs.Flush(); fs.Close(); } #endregion
#region 读取 保存 ////读取 //string strFileTxt = string.Empty; //using (FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) //{ // StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8); //选择编码方式 // strFileTxt = sr.ReadToEnd(); //} ////保存 //using (FileStream fs = new FileStream(strSavePath, FileMode.Create, FileAccess.Write)) //{ // byte[] fData = Encoding.UTF8.GetBytes(strFileTxt); // fs.Write(fData, 0, fData.Length); // fs.Flush(); //} #endregion
http://www.cnblogs.com/jx270/archive/2013/04/14/3020456.html
public static class LogHelper { private static readonly Queue<Dictionary<string, string>> Que = new Queue<Dictionary<string, string>>(); private static readonly Object Object = new Object(); private static EnumLogLevel LogType { get; set; } static LogHelper() { ThreadPool.QueueUserWorkItem(s => { while (true) { if (Que.Count <= 0) { Thread.Sleep(5000); continue; } lock (Object) { if (Que.Count <= 0) { Thread.Sleep(5000); continue; } var currentDirectory = AppDomain.CurrentDomain.BaseDirectory; var path = string.Format("{0}Logs\\", currentDirectory); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var fileName = Path.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".log"); using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (var sw = new StreamWriter(fs)) { sw.BaseStream.Seek(0, SeekOrigin.End); var col = Que.Dequeue(); foreach (KeyValuePair<string, string> m in col) { sw.WriteLine(m.Key + ":{0}", m.Value); } sw.Flush(); sw.Dispose(); sw.Close(); } } } } }); } public static string WriteLog(this string str, EnumLogLevel type = EnumLogLevel.Info) { var logLevel = ConfigurationManager.AppSettings["LogLevel"]; var level = string.IsNullOrWhiteSpace(logLevel) ? EnumLogLevel.Info.ToString() : logLevel; if ((int)type < (int)Enum.Parse(typeof(EnumLogLevel), level)) { return string.Empty; } lock (Object) { LogType = type; var st = new StackTrace(new StackFrame(1, true)); StackFrame sf = st.GetFrame(0); var dic = new Dictionary<string, string> { {"发生时间", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff dddd")}, {"日志级别", LogType.ToString()}, {"日志消息", str}, {"当前方法", sf.GetMethod().Name}, {"发生位置", st.ToString()} }; Que.Enqueue(dic); } return str; } } /// <summary> /// All: 表示最低的日志等级。 /// Debug: 这个等级表示用于调试程序的正常的事件信息; /// Info: 默认的等级 /// Warn: 表示可能对系统有损害的情况; /// Error: 表示较严重的错误等级,但是程序可以继续运行的信息; /// Fatal: 表示非常严重的错误等级,记录极有可能导致应用程序终止运行的致命错误信息; /// Off: 表示最高的等级,如果一个logger的等级标记为Off, 将不会记录任何信息; /// </summary> public enum EnumLogLevel { All, Debug, Info, Warn, Error, Fatal, Off }