tags:

views:

2140

answers:

7

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

+20  A: 

That would be File.WriteAllBytes()

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

Maurice
+3  A: 

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

Khoth
+2  A: 

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.

Adam Wright
+3  A: 

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

Guerry
A: 

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.

ramayac
A: 

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.

HTH, Kent

Kent Boogaart
+1  A: 

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.

Chris S