public async Task <Tuple <string, MemoryStream> > DownloadFileAsync(string id, string bucketName = "") { var gridFsBucket = string.IsNullOrEmpty(bucketName)? new GridFSBucket(this.database): new GridFSBucket(this.database, new GridFSBucketOptions { BucketName = bucketName }); MemoryStream destinationStream = new MemoryStream(); //await gridFsBucket.DownloadToStreamAsync(id, destinationStream); using (GridFSDownloadStream sourceStream = await gridFsBucket.OpenDownloadStreamAsync(new ObjectId(id))) { long filezise = sourceStream.Length; //缓冲区大小 int maxlenth = 4096; byte[] buffer = new byte[maxlenth]; while (filezise > 0) { if (filezise < maxlenth) { maxlenth = (int)filezise; } await sourceStream.ReadAsync(buffer, 0, maxlenth); await destinationStream.WriteAsync(buffer, 0, maxlenth); filezise -= maxlenth; } return(new Tuple <string, MemoryStream>(sourceStream.FileInfo.Filename, destinationStream)); } }
public async Task <GridFSFileInfo> DownloadFileAsync(ObjectId id, GridFSDownloadOptions options = null) { var gridFsBucket = new GridFSBucket(this.database); using (GridFSDownloadStream sourceStream = await gridFsBucket.OpenDownloadStreamAsync(id)) { long filezise = sourceStream.Length; //缓冲区大小 int maxlenth = 4096; byte[] buffer = new byte[maxlenth]; using (FileStream destinationStream = File.Open(_confg + "/" + sourceStream.FileInfo.Filename, FileMode.Create)) { while (filezise > 0) { if (filezise < maxlenth) { maxlenth = (int)filezise; } await sourceStream.ReadAsync(buffer, 0, maxlenth); await destinationStream.WriteAsync(buffer, 0, maxlenth); filezise -= maxlenth; } } return(sourceStream.FileInfo); } }