美文网首页
C#文件操作

C#文件操作

作者: qratosone | 来源:发表于2016-05-02 00:30 被阅读0次

    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#文件操作

          本文链接:https://www.haomeiwen.com/subject/gvclrttx.html