IO流中的Stream相关对象

     流无处不在,只要是关于到文件的输入、输出、更新等,关于IO流,项目中还是经常用到的,写log日志免不了要与其打交道,现在需要用到,就顺道好好回顾一下进行整理,首先是几个需要用到的类的说明,其实说简单点,就是对文件夹、文件、文件内容进行编辑。

     

1. 创建文件、文件夹

        public void OperationFile()
        {
            //创建文件
            if (!File.Exists("Log.txt"))
            {
                File.Create("Log.txt");
                           
            }

            //创建文件夹
            if (!Directory.Exists("Log"))
            {
                Directory.CreateDirectory("Log");
            }
        }

2. 读写数据到文件中

   FileStream 原始,比较复杂,处理的数据多   

读取文件数据

        public void ReadFileStream()
        {
            //打开数据
            //FileStream fs = File.OpenRead("201704191450.txt");
            //FileInfo fileinfo = new FileInfo("201704191450.txt");
            //FileStream fs = fileinfo.OpenRead();

            //读取数据
            byte[] bytedata = new byte[100];
            char[] chardata = new char[100];
            FileStream ffs = new FileStream("TestRead.txt",FileMode.Open);
            //执行文件指针位置
            ffs.Seek(10,SeekOrigin.Begin);
            //读取数据,其起始位置为seek指定的指针位置末
            ffs.Read(bytedata,0,100);
            //设置转码格式
            Decoder d = Encoding.UTF8.GetDecoder();
            d.GetChars(bytedata,0,bytedata.Length,chardata,0);
            Console.WriteLine(chardata);         
            Console.ReadKey();

        }

写入文件数据

        public void WriteFileStream()
        {
            //写入数据
            byte[] byteData = new byte[100];
            char[] charData = new char[100];
            FileStream fis = new FileStream("TestWrite.txt", FileMode.Create);
            charData = ("This is a jokey").ToArray();
            byteData = new byte[charData.Length];
            Encoder e = Encoding.UTF8.GetEncoder();
            e.GetBytes(charData, 0, charData.Length, byteData, 0, true);
            fis.Seek(0, SeekOrigin.Begin);
            fis.Write(byteData, 0, byteData.Length);
        }

由此可见,操作字符数据比较麻烦。而StreamWritrer、StreamReader不需要设置指针位置,读写文件时,比较灵活

StreamReader读取文件数据

        /// <summary>
        /// StreamReader读取日志
        /// </summary>
        public void ReadLog()
        {
            StreamReader sr = new StreamReader("201704191451.txt", true);
            string line = sr.ReadLine();
            while (line!=null)
            {
                Console.WriteLine(line);
                line = sr.ReadLine();
            }

            sr.Close();
        }

StreamWriter写入文件数据

        /// <summary>
        /// StreamWrite写入日志
        /// </summary>
        /// <param name="ex"></param>
        public void WriteExLog(string ex)
        {
            StreamWriter sw = new StreamWriter(DateTime.Now.ToString("yyyyMMddHHmm")+".txt",true);
            sw.WriteLine(DateTime.Now.ToString("G")+" "+ex);
            sw.Close();

        }

两者一进行对比,可见StreamWriter、StreamReader确实比FileStream方便很多

关于流文件的使用,上面仅仅是单一的操作,实际项目中,多为混合模式,各种判断柔和在一起,这里也不多说什么,先写一个相对来书综合点的方法

       public void OperationStream()
       {
            //当前Debug下+创建文件夹
            string straddrsfile = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar.ToString() + "Test1";
            //当前路径+文件名
            string straddrspath = straddrsfile + Path.DirectorySeparatorChar.ToString() + "Test1" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
            straddrspath = straddrspath.Replace("\\", "/");
            if (!File.Exists(straddrsfile))
            {   
                //创建文件夹
                Directory.CreateDirectory(straddrsfile);
                //创建文件
                StreamWriter sw = new StreamWriter(straddrspath,true);
                //写入数据
                sw.WriteLine(DateTime.Now.ToString("G") + "This is a jokey");
                sw.Close();
                //读取数据
                StreamReader sr = new StreamReader(straddrspath,true);
                string line = sr.ReadLine();
                //输出数据
                while (line != null)
                {
                    Console.WriteLine(line);
                    line = sr.ReadLine();
                }
                sr.Close();
                Console.ReadKey();
            }
      }

对于这些流关联的类,其重载的方法有很多,向那些参数的说明,指尖敲击下键盘,点下联想看看说明,就出来,总之,深入的研究清一个问题需要大量的时间,结果还未可知,当前项目既然需要这个日志,就稍稍巩固下。

------分割线---------------

实战:现在接手的项目中需要异常日志,初步思路如下: 

 

        //記錄異常日誌  Log file txt
        public void WriteTxtLog(Exception ex,string sysCode,string functId)
        {
            //文件夾名稱
            string logFolder = ConfigurationManager.AppSettings["LogFolder"];
            //文件名
            string logFolderName = ConfigurationManager.AppSettings["LogFolderName"];
            //文件夾路徑
            string logFolderPath = ConfigurationManager.AppSettings["LogFolderPath"];
            //文件路徑
            string path = logFolderPath + "\\" + logFolder + "\\" + DateTime.Now.ToString("yyyyMMdd") + logFolderName;
            //创建文件夹
            if (!Directory.Exists(logFolderPath+"\\"+ logFolder))
            {
                Directory.CreateDirectory(logFolderPath + "\\" + logFolder);
            }          
            //不存存在txt,則創建,存在則追加
            var sw = !File.Exists(path) == true ? new StreamWriter(path, true) : File.AppendText(path);          
            //写入数据
            sw.WriteLine("..................");
            sw.WriteLine("異常日誌,開始時間:" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
            sw.WriteLine("系統名:" + sysCode + "  功能代號:" + functId + "  異常錯誤信息:" + ex.ToString());
            sw.WriteLine("異常日誌,完成時間:" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
            sw.WriteLine("..................");
            sw.Close();
        }

 

市人皆大笑,举手揶揄之

 

posted @ 2017-04-19 17:37  郎中令  阅读(362)  评论(1编辑  收藏  举报