Memory Efficient file append
- by lboregard
i have several files whose content need to be merged into a single file. i have the following code that does this ... but it seems rather inefficient in terms of memory usage ... would you suggest a better way to do it ?
the Util.MoveFile function simply accounts for moving files across volumes
private void Compose(string[] files)
{
string inFile = "";
string outFile = "c:\final.txt";
using (FileStream fsOut = new FileStream(outFile + ".tmp", FileMode.Create))
{
foreach (string inFile in files)
{
if (!File.Exists(inFile))
{
continue;
}
byte[] bytes;
using (FileStream fsIn = new FileStream(inFile, FileMode.Open))
{
bytes = new byte[fsIn.Length];
fsIn.Read(bytes, 0, bytes.Length);
}
//using (StreamReader sr = new StreamReader(inFile))
//{
// text = sr.ReadToEnd();
//}
// write the segment to final file
fsOut.Write(bytes, 0, bytes.Length);
File.Delete(inFile);
}
}
Util.MoveFile(outFile + ".tmp", outFile);
}