[CSHARP-437] how can i insert binary data into a collection using c#. Created: 11/Apr/12  Updated: 05/Apr/19  Resolved: 11/Apr/12

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Critical - P2
Reporter: mahendar.gunda Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

how can i insert binary data(image in the form of binary data) into a collection using c#.



 Comments   
Comment by Robert Stam [ 11/Apr/12 ]

Normally we use JIRA as our bug tracking system and prefer to have questions posted on Google Groups:

https://groups.google.com/forum/?fromgroups#!forum/mongodb-user

In answer to your question, you can't insert binary data directly into the database. You have two choices:

1. Create a class that has a byte[] property to hold the binary data
2. Upload the binary data as a GridFS file

In the first case the class would look something like this:

public class C
{
    public ObjectId Id;
    public byte[] BinaryData;
}

And the code to insert a document with binary data would look something like this:

var document = new C
{
    Id = ObjectId.GenerateNewId(),
    BinaryData = new byte[] { 1, 2, 3 }
};
collection.Insert(document);

Here's what the resulting document would look like in the mongo shell:

> db.test.find()
{ "_id" : ObjectId("4f8586f5e447ad1ec82c7c07"), "BinaryData" : BinData(0,"AQID") }
>

To upload binary data using GridFS you would use code like this:

Stream sourceStream; // the source of the binary data
string remoteFileName; // the name you want the GridFS file to have
database.GridFS.Upload(sourceStream, remoteFileName);

And to download binary data using GridFS you would use code like this:

Stream destinationStream; // the destination of the binary data
string remoteFileName; // the name you want the GridFS file to have
database.GridFS.Download(destinationStream, remoteFileName);

Generated at Wed Feb 07 21:36:50 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.