zoukankan      html  css  js  c++  java
  • C# 运用StreamReader类和StreamWriter类实现文件的读写操作

    对文件的读写操作应该是最重要的文件操作,System.IO命名空间为我们提供了诸多文件读写操作类,在这里我要向大家介绍最常用也是最基本的StreamReader类和StreamWriter类。从这两个类的名称我们不难发现它们都是基于流的读写操作类。

    我们可以通过File类的OpenText()方法来获取一个StreamReader对象,通过该对象我们可以实现对文本文件的读操作,方法如下: 
     
    Console.WriteLine("Reading the contents from the file");
    StreamReader s = File.OpenText("MyText.txt");
    string read = null;
    while ((read = s.ReadLine()) != null)
    {
      Console.WriteLine(read);
    }
    s.Close(); 
    而通过调用FileInfo类的CreateText()方法我们可以获取一个StreamWriter对象,调用StreamWriter类的WriteLine()我们就可以向文本文件中写入数据了,方法如下: 
      
    FileInfo f = new FileInfo("MyText.txt")
    StreamWriter w = f.CreateText();
    w.WriteLine("This is from");
    w.WriteLine("Chapter 1");
    w.WriteLine("Of C# Module");
    w.Write(w.NewLine);
    w.WriteLine("Thanks for your time");
    w.Close(); 

     
  • 相关阅读:
    Core Java Interview Question Answer
    Anagrams
    Permutations II
    Minimum Window Substring
    工厂模式
    How do you design object oriented projects?
    What is Object Oriented Design? (OOD)
    Amazon Interview Question: Design an OO parking lot
    讨论一道求质数的面试题
    Substring with Concatenation of All Words
  • 原文地址:https://www.cnblogs.com/melao2006/p/4239656.html
Copyright © 2011-2022 走看看