Could I return a FileStream as a generic interface to a file?
I'm writing a class interface that needs to return references to binary files. Typically I would provide a reference to a file as a file path. However, I'm considering storing some of the files (such as a small thumbnail) in a database directly rather then on a file system. In this case I don't want to add the extra step of reading the thumbnail out of the database onto the disc and then returning a path to the file for my program to read. I'd want to stream the image directly out of the database into my program and avoid writing anything to the disc unless the user explicit wants to save something.
Would having my interface return a FileStream
or even a开发者_C百科 Image
make sense? Then it would be up to the implementing class to determine if the source of the FileStream
or Image
is a file on a disc or binary data in a database.
public interface MyInterface
{
string Thumbnail {get;}
string Attachment {get;}
}
vs
public interface MyInterface
{
Image Thumbnail {get;}
FileStream Attachment {get;}
}
You could return a Stream
object that streams to either a file or a database
You can. However I would change the interface to look more like:
public interface MyInterface
{
Image CreateThumbnail();
FileStream CreateAttachment();
}
This resolves any ambiguity about the lifetime of the returned objects; keeping them from being disposed out from under you for instance.
For small content where the usage is clear like a thumbnail I think you would be better off returning the type as it will be used (i.e. Image). If you've got large content where the purpose may vary or they may be reasons to read it partially then Stream is they way to go. In either case the source of the content is hidden from the user of the class. You will also want to consider the dispose semantics of the stream and whether or not you want the user of the class to have control over how long a database connection stays open.
You could use a byte[]
to represent the file if its size is not very big and fits into memory. Otherwise a Stream is good but make sure you implement IDisposable to release it properly.
精彩评论