Skip to content

Instantly share code, notes, and snippets.

@oec2003
Created May 19, 2015 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oec2003/6c1d473a5a5b61a9d131 to your computer and use it in GitHub Desktop.
Save oec2003/6c1d473a5a5b61a9d131 to your computer and use it in GitHub Desktop.
GridFS操作类
public class GridFSHandle : IDFSHandle
{
private readonly MongoDatabase _db;
private readonly MongoServer _server;
private readonly string _dbName;
private readonly MongoGridFS _gridFs;
private readonly string _connectionString;
public GridFSHandle()
{
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MongoConnectionString"].ToString();
_dbName = System.Configuration.ConfigurationManager.AppSettings["MongoDBName"];
_server = MongoServer.Create(_connectionString);
_db = _server.GetDatabase(_dbName);
_gridFs = _db.GridFS;
}
public GridFSHandle(string connectionString,string dbName)
{
_connectionString = connectionString;
_dbName = dbName;
}
public string AddFile(Stream fileStream, string fileName)
{
MongoGridFSFileInfo fileInfo = _gridFs.Upload(fileStream, fileName);
return fileInfo.Id.ToString();
}
public bool DeleteFile()
{
throw new NotImplementedException();
}
public string IsExist(string tag)
{
string id = "";
var files = _gridFs.Find(Query.EQ("md5", BsonValue.Create(tag)));
if(files.Count() > 0)
{
id=files.FirstOrDefault().Id.ToString();
}
return id;
}
public Stream GetFile(string fileId)
{
ObjectId id = ObjectId.Parse(fileId);
var file = _gridFs.FindOneById(id);
return file != null ? file.OpenRead() : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment