NvMat NvMat - 1 month ago 8
C# Question

Storing a file as a byte array or a stream in an object?

I was wondering which way is a better way to store a file? As a property in an object using a

Stream
, or a byte array (
byte[]
)?

For example:

public class FileObject
{
public string SomeMetaData {get; set;}
public Stream Content {get; set;}
}


vs

public class FileObject
{
public string SomeMetaData {get; set;}
public byte[] Content {get; set;}
}


I have an object that stores some meta data about a file and it also has the file content of the file. This class will act as a container for the file so I can do some logic based on its meta data before I save it.

I know if I use Stream I have to call Dispose before I'm done with it, which makes it harder to pass the object around without worrying about its content being disposed. However I'm not sure if that is a real issue or there are other things that I need to keep in mind.

Answer

A stream is a stateful object. If two pieces of code use your class together, they will end up fighting over the stream's position, and will not work.

If that is at all likely to happen, you should definitely use a byte[].