Could I return a FileStream as a generic interface to a file?

佐手、 提交于 2019-12-11 08:35:20

问题


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 FileStreamor even a Imagemake 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;}
}

回答1:


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.




回答2:


You could return a Stream object that streams to either a file or a database




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2767954/could-i-return-a-filestream-as-a-generic-interface-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!