Jack
Jack

Reputation: 5768

File.WriteAllBytes or FileStream.Write

What's the difference between File.WriteAllBytes and FileStream.Write/WriteBytes? I have a bitmap object that and I want to create a new bmp/jpg/png on disk. I think I read somewhere that WriteAllBytes uses FileStream.Write underneath?

Upvotes: 7

Views: 11045

Answers (4)

Jonas
Jonas

Reputation: 589

You should use WriteAllBytes if you want to save a bitmap.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941347

You're on the wrong track with this. Saving a bitmap object requires Image.Save(). That's a method that knows how to use an image encoder to convert a bitmap into the bytes that another program (or yours) can load back. There are several image encoders, you can select the one you want with the Save() overload that lets you pick the ImageFormat. The BMP format is the native Windows format, it is uncompressed. The PNG format is nice, it is a compressed lossless format. The JPEG format is a compressed lossy format, good for photos. File size is big to small in order.

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

Use WriteAllBytes to just save all the bytes, use Write if you need to watch the progress.

Upvotes: 3

driis
driis

Reputation: 164291

WriteAllBytes is just a convinience method, that wraps the underlying Stream operations. (Create a file, write to stream, close stream, etc). Use it if it fits your needs. If you need more control on the underlying operations, fallback to using a Streamor similar.

It is all about using the right abstraction for the task.

Upvotes: 18

Related Questions