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");
}
}
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");
}
}
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET