Skip to content

Instantly share code, notes, and snippets.

@oec2003
Created May 19, 2015
Embed
What would you like to do?
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