• 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();

  • 相关阅读:
    Delphi: TMemo垂直滚动条自动显示
    利用百度地图API制作房产酒店地图
    百度地图API--信息窗口
    Echarts饼状图
    JS截取与分割字符串常用技巧总结
    JS DOM1核心概要document
    JS DOM1核心概要1
    phpMVC框架的核心启动类定义
    jquery实现无限滚动瀑布流实现原理
    php连接数据库步骤
  • 原文地址:https://www.cnblogs.com/zhangruisoldier/p/4226994.html
Copyright © 2020-2023  润新知