What is the most efficient way to save a byte array as a file on disk in C#?

前端 未结 7 1160

Pretty simple scenario. I have a web service that receives a byte array that is to be saved as a particular file type on disk. What is the most efficient way to do this in C#?

相关标签:
7条回答
  • 2021-02-06 20:36

    I had a similar problem dumping a 300 MB Byte array to a disk file...
    I used StreamWriter, and it took me a good 30 minutes to dump the file.
    Using FilePut took me arround 3-4 minutes, and when I used BinaryWriter, the file was dumped in 50-60 seconds.
    If you use BinaryWriter you will have a better performance.

    0 讨论(0)
  • 2021-02-06 20:42

    That would be File.WriteAllBytes().

    0 讨论(0)
  • 2021-02-06 20:44

    Actually, the most efficient way would be to stream the data and to write it as you receive it. WCF supports streaming so this may be something you'd want to look into. This is particularly important if you're doing this with large files, since you almost certainly don't want the file contents in memory on both the server and client.

    0 讨论(0)
  • 2021-02-06 20:45

    Perhaps the System.IO.BinaryWriter and BinaryReader classes would help.

    http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx

    "Writes primitive types in binary to a stream and supports writing strings in a specific encoding."

    http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx

    "Reads primitive data types as binary values in a specific encoding."

    0 讨论(0)
  • 2021-02-06 20:52

    System.IO.File.WriteAllBytes(path, data) should do fine.

    0 讨论(0)
  • 2021-02-06 20:53

    Not sure what you mean by "efficient" in this context, but I'd use System.IO.File.WriteAllBytes(string path, byte[] bytes) - Certainly efficient in terms of LOC.

    0 讨论(0)
提交回复
热议问题