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();
                }
    
            }
  • 相关阅读:
    记录使用cx_Freeze打包Python成exe可执行程序
    jquery plug-in DataTable API中文文档参考
    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/xxx/lib/arm/liblame.so: has text relocations
    CocoaPods的安装及使用
    Android 贝塞尔曲线的浅析
    GUI学习中错误Exception in thread "main" java.lang.NullPointerException
    线程
    12月13日
    今天开始学习java编程
    UVA10140 Prime Distance
  • 原文地址:https://www.cnblogs.com/su-king/p/5122007.html
Copyright © 2011-2022 走看看