C#文件读写操作

新建一个Log.txt文件
引入System.IO名称空间,用文件流
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace StreamWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(aFile);

                bool truth = true;
                // Write data to file.
                sw.WriteLine("Hello to you.");
                sw.WriteLine("It is now {0} and things are looking good.",
                    DateTime.Now.ToLongDateString());
                sw.Write("More than that,");
                sw.Write(" it's {0} that C# is fun.", truth);
                sw.Close();
            }
            catch (IOException ex)
            {
                Console.WriteLine("An IOException has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                return;
            }
        }
    }
}

读取文件,这里介绍StreamReader对象
static void Main(string[] args)
{
     string strLine;
     try
     {
            FileStream aFile = new FileStream("Log.txt",FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            strLine = sr.ReadLine();
            //Read data in line by line 这个兄台看的懂吧~一行一行的读取
      while(strLine != null)
            {
                Console.WriteLine(strLine);
                Line = sr.ReadLine();
             }
            sr.Close();
       }catch (IOException ex)
            {
                Console.WriteLine("An IOException has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                return;
            }
}
另外对于简单的文档可以直接sr.ReadToEnd()从头读到尾,还有sr.Read() 返回类型char。这些兄台可以自己看书去学
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值