码迷,mamicode.com
首页 > Windows程序 > 详细

C# txt文件读写

时间:2016-01-11 20:01:16      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

 

//读取文件内容

(1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出。

byte[] byData = new byte[100];
        char[] charData = new char[1000];
        public void Read()
        {
            try
            {
                FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
                file.Seek(0, SeekOrigin.Begin);
                file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
                Decoder d = Encoding.Default.GetDecoder();
                d.GetChars(byData, 0, byData.Length, charData, 0);
                Console.WriteLine(charData);
                file.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
        }

(2).使用StreamReader读取文件,然后一行一行的输出。

public void Read(string path)
        {
            StreamReader sr = new StreamReader(path,Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line.ToString());
            }
        }

 

 

//写文件

        //写日志
        public void fileWriter(string info)
        {

            //获取当前服务器的路径
            string file = HttpContext.Current.Server.MapPath("~/logs/" + System.DateTime.Now.Year + System.DateTime.Now.Month + "log.log");
            if (File.Exists(file) == true)
            {
                StreamWriter mySw = new StreamWriter(file, true);
                mySw.WriteLine("");
                mySw.WriteLine(System.DateTime.Now);
                mySw.WriteLine(info);
                mySw.Close();
            }
            else
            {
                using (File.Create(file)) ;
                StreamWriter mySw = new StreamWriter(file, true);
                mySw.WriteLine("");
                mySw.WriteLine(System.DateTime.Now);
                mySw.WriteLine(info);
                mySw.Close();
            }

        }

 

C# txt文件读写

标签:

原文地址:http://www.cnblogs.com/su-king/p/5122007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!