Created
May 19, 2015 15:50
-
-
Save oec2003/6c1d473a5a5b61a9d131 to your computer and use it in GitHub Desktop.
GridFS操作类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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