1 using MongoDB.Driver; 2 using MongoDB.Driver.GridFS; 3 using System.IO; 4 5 namespace Wisdombud.Mongo 6 { 7 /// <summary> 8 /// 9 /// </summary> 10 public class MongoFileBll 11 { 12 private MongoDatabase repository; 13 /// <summary> 14 /// 15 /// </summary> 16 /// <returns></returns> 17 public MongoCursor<MongoGridFSFileInfo> FindAll() 18 { 19 return this.repository.GetGridFS(MongoGridFSSettings.Defaults).FindAll(); 20 } 21 /// <summary> 22 /// 23 /// </summary> 24 /// <param name="pConnectionstring"></param> 25 public MongoFileBll(string pConnectionstring) 26 { 27 MongoUrl mongourl = MongoUrl.Create(pConnectionstring); 28 var client = new MongoClient(mongourl); 29 MongoServer server = client.GetServer(); 30 this.repository = server.GetDatabase(mongourl.DatabaseName); 31 } 32 /// <summary> 33 /// 34 /// </summary> 35 /// <param name="filePath"></param> 36 public void UploadFile(string filePath) 37 { 38 FileInfo fi = new FileInfo(filePath); 39 this.repository.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fi.Name); 40 } 41 /// <summary> 42 /// 43 /// </summary> 44 /// <param name="filePath"></param> 45 /// <param name="fileName"></param> 46 47 public void UploadFile(string filePath, string fileName) 48 { 49 this.repository.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fileName); 50 } 51 52 /// <summary> 53 /// 54 /// </summary> 55 /// <param name="fileName"></param> 56 /// <param name="filePath"></param> 57 public void DownloadFile(string fileName) 58 { 59 this.repository.GetGridFS(MongoGridFSSettings.Defaults).Download(fileName); 60 } 61 /// <summary> 62 /// 63 /// </summary> 64 /// <param name="fileName"></param> 65 public void DeleteFile(string fileName) 66 { 67 this.repository.GetGridFS(MongoGridFSSettings.Defaults).Delete(fileName); 68 } 69 /// <summary> 70 /// 71 /// </summary> 72 public void DeleteAll() 73 { 74 foreach (var inst in this.repository.GetGridFS(MongoGridFSSettings.Defaults).FindAll()) 75 { 76 inst.Delete(); 77 } 78 } 79 } 80 }
使用方法
1 MongoFileBll tl = new MongoFileBll("mongodb://127.0.0.1:27017/chzhaotest"); 2 string folder = @"D:Wisdombud201620160324_Wisdombud.MongoSourceCodeWisdombud.Mongo.SamplebinDebug"; 3 DirectoryInfo di = new DirectoryInfo(folder); 4 foreach (var file in di.GetFiles()) 5 { 6 tl.UploadFile(file.FullName, Guid.NewGuid().ToString()); 7 } 8 var aaa = tl.FindAll(); 9 foreach (var inst in aaa) 10 { 11 Console.WriteLine(inst.Name); 12 }