C#使用StreamWriter类和StreamReader类读写文件综合实例

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

public class MyClass
{
public static void Main()
{
   try
   {
    //创建FileStream对象
    FileStream fs=new FileStream("c:\\my.txt",FileMode.OpenOrCreate);
    //创建StreamWriter对象
    StreamWriter sw=new StreamWriter(fs);
    //换行写入数据
    sw.WriteLine("Hello World!");
    sw.WriteLine("C#");
    //不换行写入
    sw.Write("努力学习,");
    sw.Write("天天向上");
    //关闭数据流
    sw.Close();
   
   }
   catch (IOException e)
   {
    Console.WriteLine(e.Message);
   }

   try
   {  
    //创建StreamReader对象
    StreamReader sr=new StreamReader("c:\\my.txt");
    //从开始到末尾
    Console.WriteLine(sr.ReadToEnd());
    //关闭数据流
    sr.Close();

   }
   catch (IOException e)
   {
    Console.WriteLine(e.Message);
   }
   finally
   {
    Console.ReadKey();
   }
}
}

posted on 2012-07-02 09:25  流星落  阅读(600)  评论(0编辑  收藏  举报

导航