1

我有几个文件的内容需要合并到一个文件中。我有以下代码可以做到这一点......但在内存使用方面似乎相当低效......你会建议一个更好的方法吗?

Util.MoveFile 函数只是考虑跨卷移动文件

   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);

}

4

2 回答 2

1

有时调用 shell 函数比重新实现功能更好。正如 Alan 所说,您可以在 unix 系统上使用 CAT,或者在 Windows 上可以使用内置的命令处理器

copy file1+file2+file3 concated_file
于 2010-06-01T03:06:34.633 回答
0

You can use smaller fixed-size buffers like so:

byte[] bytes = new byte[8192]; // adjust this as needed
int bytesRead;
do {
    bytesRead = fsIn.Read(bytes, 0, bytes.Length);
    fsOut.Write(bytes, 0, bytesRead);
} while (bytesRead > 0);

This is pretty self explanatory except for during the last block so basically what's happening is I'm passing an 8K byte array to the Read method which returns the number of bytes it actually read. So on the Write call, I am passing that value which is somewhere between 0 and 8192. In other words, on the last block, even though I am passing a byte array of 8192 bytes, bytesRead might only be 10 in which case only the first 10 bytes need to be written.

EDIT

I edited my answer to do this in a slightly different way. Instead of using the input file's position to determine when to break out of the loop, I am checking to see if bytesRead is greater than zero. This method works with any kind of stream to stream copy including streams that don't have a fixed or known length.

于 2010-06-01T03:08:25.950 回答