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

C#.Net

C# Problem Overview


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#?

C# Solutions


Solution 1 - C#

That would be File.WriteAllBytes().

Solution 2 - C#

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

Solution 3 - C#

And WriteAllBytes just performs

using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
	stream.Write(bytes, 0, bytes.Length);
}

BinaryWriter has a misleading name, it's intended for writing primitives as a byte representations instead of writing binary data. All its Write(byte[]) method does is perform Write() on the stream its using, in this case a FileStream.

Solution 4 - C#

Not sure what you mean by "efficient" in this context, but I'd use http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx">System.IO.File.WriteAllBytes(string path, byte[] bytes) - Certainly efficient in terms of LOC.

Solution 5 - C#

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."

Solution 6 - C#

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.

Solution 7 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKilhofferView Question on Stackoverflow
Solution 1 - C#MauriceView Answer on Stackoverflow
Solution 2 - C#KhothView Answer on Stackoverflow
Solution 3 - C#Chris SView Answer on Stackoverflow
Solution 4 - C#Adam WrightView Answer on Stackoverflow
Solution 5 - C#GuerryView Answer on Stackoverflow
Solution 6 - C#ràmäyácView Answer on Stackoverflow
Solution 7 - C#Kent BoogaartView Answer on Stackoverflow