C#实现文本文件合并

 

复制代码
 
读取n个文本文件,把文件内容合并到一个文本文件中。主要用了FileStream的ReadByte和WriteByte方法。
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(); 
                    } 
                     
                } 
            } 
     } 



调用方法如下:

 
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"); 
    } 
复制代码

 

posted @   跟着阿笨一起玩.NET  阅读(2387)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?
点击右上角即可分享
微信分享提示