C#实现文本文件合并
时间:2011-06-13 来源:zhouhb
读取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");
}
}