zoukankan      html  css  js  c++  java
  • C# txt文件读写

    //读取文件内容

    (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();
                }
    
            }
  • 相关阅读:
    POJ 1681 Painter's Problem(高斯消元法)
    HDU 3530 Subsequence(单调队列)
    HDU 4302 Holedox Eating(优先队列或者线段树)
    POJ 2947 Widget Factory(高斯消元法,解模线性方程组)
    HDU 3635 Dragon Balls(并查集)
    HDU 4301 Divide Chocolate(找规律,DP)
    POJ 1753 Flip Game(高斯消元)
    POJ 3185 The Water Bowls(高斯消元)
    克琳:http://liyu.eu5.org
    WinDbg使用
  • 原文地址:https://www.cnblogs.com/su-king/p/5122007.html
Copyright © 2011-2022 走看看