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

    namespace file
    {
    class MyFile
    {
    string FilePath;
    byte[] byData = new byte[100];
    public char[] MyData = new char[1000];
    public string reslutstr = null;
    public MyFile()
    { }
    public MyFile(string path)
    {
    FilePath = path;
    }
    public void ReadFile1()
    {
    try
    {
    FileStream file = new FileStream(FilePath, 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, MyData, 0);
    //Console.WriteLine(MyData);
    foreach (char ch in MyData)
    {
    reslutstr += ch.ToString();
    }
    file.Close();
    }
    catch (IOException e)
    {
    Console.WriteLine(e.ToString());
    }
    }
    public void ReadFile2()
    {
    StreamReader sr = new StreamReader(FilePath, Encoding.Default);
    String line;
    while ((line = sr.ReadLine()) != null)
    {
    reslutstr += line;
    // Console.WriteLine(line.ToString());
    }
    }
    public void SaveFile1(string savestr)
    {
    FileStream fs = new FileStream(FilePath, FileMode.Create);
    //获得字节数组
    byte[] data = System.Text.Encoding.Default.GetBytes(savestr);
    //开始写入
    fs.Write(data, 0, data.Length);
    //清空缓冲区、关闭流
    fs.Flush();
    fs.Close();
    }

    public void SaveFile2()
    {
    FileStream fs = new FileStream(FilePath, FileMode.Create);
    StreamWriter sw = new StreamWriter(fs);
    //开始写入
    sw.Write("Hello World!!!!");
    //清空缓冲区
    sw.Flush();
    //关闭流
    sw.Close();
    fs.Close();
    }
    }
    }
    //调用方法:
    MyFile MyFile = new MyFile(Filepath);
    string result = null;
    // MyFile.SaveFile1(savastr);
    MyFile.SaveFile2();
    MyFile.ReadFile2();

  • 相关阅读:
    HTTP学习笔记(1)ULR语法
    wsdl地址如何在远程服务器上查看源码?
    java线程详解(三)
    java线程详解(二)
    java线程详解(一)
    java中this用法总结
    Linux运行python程序
    如何获取到Java对象的地址
    IDEA 远程调试
    linux环境中mysql默认端口3306无法连接问题排查
  • 原文地址:https://www.cnblogs.com/zhangruisoldier/p/4226994.html
Copyright © 2011-2022 走看看