C#实现文本文件合并 _17

读取n个文本文件,把文件内容合并到一个文本文件中。重要用了FileStream的ReadByte跟WriteByte办法。

 
  1. class FileCombine
  2. {
  3.      public void CombineFile(String[] infileName,String outfileName)
  4.      {     
  5.             int b;
  6.             int n=infileName.Length;
  7.             FileStream[] fileIn=new FileStream[n];
  8.             using (FileStream fileOut = new FileStream(outfileName, FileMode.Create))
  9.             {
  10.                 for (int i = 0; i < n; i++)
  11.                 {
  12.                     try
  13.                     {
  14.                         fileIn[i] = new FileStream(infileName[i], FileMode.Open);
  15.                         while ((b = fileIn[i].ReadByte()) != -1)
  16.                             fileOut.WriteByte((byte)b);
  17.                     }
  18.                     catch (System.Exception ex)
  19.                     {
  20.                         Console.WriteLine(ex.Message);
  21.                     }
  22.                     finally
  23.                     {
  24.                         fileIn[i].Close();
  25.                     }
  26.                     
  27.                 }
  28.             }
  29.      }
  30. }
class FileCombine
{
     public void CombineFile(String[] infileName,String outfileName)
     {     
            int b;
            int n=infileName.Length;
            FileStream[] fileIn=new FileStream[n];
            using (FileStream fileOut = new FileStream(outfileName, FileMode.Create))
            {
                for (int i = 0; i < n; i++)
                {
                    try
                    {
                        fileIn[i] = new FileStream(infileName[i], FileMode.Open);
                        while ((b = fileIn[i].ReadByte()) != -1)
                            fileOut.WriteByte((byte)b);
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        fileIn[i].Close();
                    }
                    
                }
            }
     }
}

调用方式如下:

 
  1. class TestCombine
  2. {
  3.      public static void Main(String[] args)
  4.      {
  5.          FileCombine c=new FileCombine();
  6.          String[] file=new String[2];
  7.          file[0]="aa.txt";
  8.          file[1]="bb.txt";
  9.          c.CombineFile(file,"cc.txt");
  10.     }
  11. }
class TestCombine
{
     public static void Main(String[] args)
     {
         FileCombine c=new FileCombine();
         String[] file=new String[2];
         file[0]="aa.txt";
         file[1]="bb.txt";
         c.CombineFile(file,"cc.txt");
    }
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值