数据写入txt文件

1. 以前写入的保留


 public static void Write(string strs)
        {
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory; //获取当前系统所在的盘符
            FileStream fs = new FileStream(filePath+"test.txt", FileMode.Append, FileAccess.Write);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(strs);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

 

 方法二: 后写的覆盖前面写入的

 #region 写日志(用于跟踪) + WriteLog(string strMemo, string path = "*****")
        /// <summary>
        /// 写日志(用于跟踪)
        /// 如果log的路径修改,更改path的默认值
        /// </summary>
        public void WriteLog(string strMemo)
        {
              string filePath = System.AppDomain.CurrentDomain.BaseDirectory; //获取当前系统所在的盘符
            //string filename = Server.MapPath(path);
            StreamWriter sr = null;
            try
            {
                FileStream fs = new FileStream(filePath+"test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs); // 创建写入流
                sw.WriteLine(strMemo); // 写入Hello World
                sw.Close(); //关闭文件
                
            }
            catch
            {

            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
        #endregion

 

posted @ 2019-10-12 10:37  大黄人  阅读(1310)  评论(0编辑  收藏  举报