11

How do I read a raw byte array from any file, and write that byte array back into a new file?

4

4 回答 4

7

(edit: note that the question changed; it didn't mention byte[] initially; see revision 1)

Well, File.Copy leaps to mind; but otherwise this sounds like a Stream scenario:

    using (Stream source = File.OpenRead(inPath))
    using (Stream dest = File.Create(outPath)) {
        byte[] buffer = new byte[2048]; // pick size
        int bytesRead;
        while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
            dest.Write(buffer, 0, bytesRead);
        }
    }
于 2009-09-20T07:59:02.823 回答
5
byte[] data = File.ReadAllBytes(path1);
File.WriteAllBytes(path2, data);
于 2009-09-20T08:07:05.497 回答
3

Do you know about TextReader and TextWriter, and their descendents StreamReader and StreamWriter? I think these will solve your problem because they handle encodings, BinaryReader does not know about encodings or even text, it is only concerned with bytes.

How to read text from a file

How to write text to a file

This is an excellent intro to file IO and encodings.

于 2009-09-20T07:59:46.207 回答
0

添加最新的答案,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest);
    }
}

您可以选择指定缓冲区大小

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest, 2048); // or something bigger.
    }
}

或者你可以在另一个线程上执行操作,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        await source.CopyToAsync(dest);
    }
}

当主线程必须执行其他工作时,这将很有用,例如 WPF 和 Windows Store 应用程序。

于 2013-06-21T08:13:31.010 回答