C#文件操作

C#中文件操作主要可以使用StreamReaderStreamWriter两个类

         string infname = "CopyFileAddLineNumber.cs";
         string outfname = "CopyFileAddLineNumber.txt";
         if( args.Length >= 1 ) infname = args[0];
         if( args.Length >= 2 ) outfname = args[1];
   
         try 
         {
             FileStream fin = new FileStream( 
                 infname, FileMode.Open, FileAccess.Read );
             FileStream fout = new FileStream(
                 outfname, FileMode.Create, FileAccess.Write );
   
             StreamReader brin = new StreamReader( 
                 fin, System.Text.Encoding.Default );
             StreamWriter brout  = new StreamWriter(
                 fout, System.Text.Encoding.Default );
   
             int cnt = 0; // 行号
             string s = brin.ReadLine();
             while ( s != null ) 
             {
                 cnt ++; 
                 s = deleteComments(s);                        //去掉以//开始的注释
                 brout.WriteLine(cnt + ": \t" + s );           //写出
                 Console.WriteLine(cnt + ": \t" + s );     //在控制上显示
                 s = brin.ReadLine();                      //读入
             }           
             brin.Close();               // 关闭缓冲读入流及文件读入流的连接.
             brout.Close();
         } 
         catch (FileNotFoundException) 
         {
             Console.WriteLine("File not found!" );
         } 
         catch (IOException e2) 
         {
             Console.WriteLine( e2 );
         }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • c++文件操作详解 C++ 通过以下几个类支持文件的输入输出: ofstream: 写操作(输出)的文件类 (由o...
    鲍陈飞阅读 1,814评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • 生活永远不可能像我们想像的那样好,但也不会像我们想像的那样糟糕,无论是好的时候,还是糟糕的时候,都一定要坚强。——...
    感恩日记微幸福阅读 379评论 0 0
  • 21年前的今天,美国说唱歌手2Pac因枪伤导致呼吸道及心脏衰竭,不治身亡,年仅25岁,一颗熠熠发光、前途无量的嘻哈...
    独行侠者阅读 311评论 0 3