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();
                }
    
            }
  • 相关阅读:
    【C-数据类型 常量 变量】
    【OC简介-类和对象】
    【ios面试总结】
    【OC基础语法考试】
    【C-01关键字】
    UI3
    ui2
    UI
    C++使用shell命令
    字典
  • 原文地址:https://www.cnblogs.com/su-king/p/5122007.html
Copyright © 2011-2022 走看看