/// <summary> /// 字节数组方式保存文件 /// </summary> /// <param name="fileData">数据内容</param> /// <param name="fileName">文件名</param> /// <param name="fileCollectionName"></param> public virtual void SaveFileByByteArray(byte[] fileData, string fileName, string fileCollectionName) { try { if (0 == fileData.Length || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileCollectionName)) { throw new KnownException("缺失必需数据,无法保存数据!"); } MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = fileCollectionName }; //MongoGridFS fs = new MongoGridFS(_database, fsSetting); // 将被遗弃的方法 MongoGridFS fs = new MongoGridFS(_server, _database.Name, fsSetting); MongoGridFSCreateOptions option = new MongoGridFSCreateOptions { UploadDate = DateTime.Now }; using (MongoGridFSStream gfs = fs.Create(fileName, option)) { gfs.Write(fileData, 0, fileData.Length); gfs.Close(); } } catch (Exception ex) { throw ex; } // 设定查询集合的名称 }
public void TestReadAllGridFS2TextAndAddText() { var server = MongoServer.Create("mongodb://localhost:27017"); var db = server.GetDatabase("dcm"); var gridSettings = new MongoGridFSSettings(); MongoGridFS fs = db.GetGridFS(gridSettings); var fileInfo = fs.Find(Query.EQ("filename", "D:\\Download\\FileTestUpload\\Hello2.txt")); int index = 0; foreach (var item in fileInfo) { MongoGridFSStream readerFS = item.Open(System.IO.FileMode.Open); StreamReader reader = new StreamReader(readerFS); string text = reader.ReadToEnd(); Console.WriteLine("####### {0}", ++index); Console.WriteLine(text); byte[] byteArray = Encoding.ASCII.GetBytes(" bon"); readerFS.Write(byteArray, 0, byteArray.Count()); readerFS.Close(); } }