简体   繁体   中英

How to retrieve a pdf from MongoDB database using c#

I have a collection of pdf files saved to MongoDB. I'm attempting to convert all the files to base64 but I'm having trouble retrieving the actual files from the database. The file path is not what I'm expecting and I'm unsure of what else to try

Below is the code I have tried. The error message is:

"System.IO.IOException Message=The filename, directory name, or volume label syntax is incorrect. : 'C:\Users\Jabari.LAPTOP-FERO3UB5\Desktop\codebase\LMO\API\LMO.Api\https:\LMOdevstorage.blob.core.windows.net\documents\57a36b7e6789102ddf\J_Broomstick58059342787ba42f12345.pdf'

From what I can see it's trying to pull from my local codebase and not the actual database. I'm not sure why this is. I'm new to MongoDB operations.

Below is my code

var file = document.AzureDocumentUri;
if (file != null)
{
    Byte[] bytes = File.ReadAllBytes(file);
    String base64String = Convert.ToBase64String(bytes);
    StreamWriter sw64 = new StreamWriter($"{filePath}test64.txt");
    sw64.Write(base64String);
    sw64.Close();
    sw64.Dispose();
}

What I'm expecting to happen is to be able to access the pdf file directly from the database and read it into memory then convert it to base64.

Why is it attempting to download from my local directory instead the collection from the database?

Byte[] bytes = File.ReadAllBytes(file);

is strange, you can't download URI like this.

To find the best way to use file in MongoDB look at GridFS.

MemoryStream ms = new MemoryStream(new byte[] { 0x00, 0x01, 0x02 }); ms.Position = 0; // MemoryStream ms2 = new MemoryStream(await File.ReadAllBytesAsync("test.pdf"));

// Write to MongoDB
// There is a limitation of 16 MB in record size for mongodb, this what GridFS handle, unlimited file size.
// https://www.mongodb.com/docs/manual/core/document/#:~:text=Document%20Size%20Limit,MongoDB%20provides%20the%20GridFS%20API.
GridFSBucket gridFSBucket = new GridFSBucket(db);
ObjectId id = await gridFSBucket.UploadFromStreamAsync("exemple.bin", ms);

// Get the file
MemoryStream ms3 = new MemoryStream();
await gridFSBucket.DownloadToStreamAsync(id, ms3);

Full example here

https://github.com/iso8859/learn-mongodb-by-example/blob/main/do.net/02%20-%20Intermediate/StoreFile.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM