zoukankan      html  css  js  c++  java
  • C#中对文件的读写

    FileStream-------表示可以被写或被读,或二者都可的文件,此文件可以同步或异步读和写
    StreamReader------从流中读取字符数据,并可通过使用 FileStream被创建为基类。
    StreamWriter------向流写字符数据,可通过使用FileStream被创建为基类。

    1. 利用StreamWriter,StreamReader实现对文件的读写:
                StreamWriter sw = new StreamWriter("D:\\firsttext.txt", true);
                sw.WriteLine("you ran the StreamWriteDemo program on:");
                sw.WriteLine(DateTime.Now);
                sw.Close();

                StreamReader sr = new StreamReader("D:\\firsttext.txt");
                string strline = null;
                while ((strline = sr.ReadLine()) != null)
                {
                    Console.WriteLine(strline);
                }


    2. 利用FileStream构造StreamWriter和StreamReader来读写文件
                    FileStream fs = new FileStream("D:\\firsttext.txt", FileMode.Append);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine("Are you Fightting now?");
                    sw.Close();

                     FileStream fsread = new FileStream("D:\\firsttext.txt", FileMode.OpenOrCreate, FileAccess.Read);
                    StreamReader sr = new StreamReader(fsread);
                    while ((strline = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(strline);
                    }

    3. 利用FileStream读写文件
                FileStream fwrite = new FileStream("D:\\stream.txt", FileMode.Append, FileAccess.Write);
                string str = Console.ReadLine();
                byte[] bt = new byte[1000];
                bt = Encoding.ASCII.GetBytes("\n" + str);
                fwrite.Write(bt, 0, str.Length);
                fwrite.Close();

                FileStream fread = new FileStream("D:\\stream.txt", FileMode.OpenOrCreate, FileAccess.Read);
                byte[] btread = new byte[1000];
                fread.Read(btread, 0, 1000);
                string s = Encoding.ASCII.GetString(btread);
                fread.Close();

  • 相关阅读:
    Ubuntu(Linux) + mono + jexus +asp.net MVC3 部署
    爬虫代理
    爬取文件时,对已经操作过的URL进行过滤
    Scrapy项目创建以及目录详情
    Scrapy 框架 安装
    爬虫案例
    爬虫基础以及 re,BeatifulSoup,requests模块使用
    Django_Admin操作
    django 权限管理permission
    Node--01
  • 原文地址:https://www.cnblogs.com/mqingqing123/p/1808099.html
Copyright © 2011-2022 走看看