/// <summary> /// 删除文件 /// </summary> /// <param name="strFileName"></param> public static void DelFile(String strFileName) { MongoDatabase mongoDB = SystemManager.GetCurrentDataBase(); MongoGridFS gfs = mongoDB.GetGridFS(new MongoGridFSSettings()); gfs.Delete(strFileName); }
public void ExcluirArquivo(string id) { //Todo: Verificar se o arquivo existe no banco! antes de tentar excluir var mySetting = new MongoGridFSSettings(); var gfs = new MongoGridFS(server, database.Name, mySetting); gfs.Delete(Query.EQ("_id", new BsonObjectId(new ObjectId(id)))); }
//delete from GridFS (old api) public static void deleteFromGridFS(string imeFajla) { var client = new MongoClient("mongodb://localhost"); var server = client.GetServer(); var database = server.GetDatabase("docs"); var gridFs = new MongoGridFS(database); gridFs.Delete(imeFajla); }
/// <summary> /// deletes file /// </summary> /// <param name="filepath"></param> public void Delete(string filepath) { if (string.IsNullOrWhiteSpace(filepath)) { throw new ArgumentException("filepath cannot be null or empty"); } //all filepaths are lowercase and all starts with folder separator filepath = filepath.ToLowerInvariant(); if (!filepath.StartsWith(FOLDER_SEPARATOR)) { filepath = FOLDER_SEPARATOR + filepath; } var sourceQuery = Query.EQ("filename", filepath); if (gfs.Exists(sourceQuery)) { gfs.Delete(sourceQuery); } }
/// <summary> /// 删除文件 /// </summary> /// <param name="remoteFile"></param> public void Delete(string remoteFile) { _logger.DebugFormat("Delete File, Id:{0}", remoteFile); try { MongoGridFS fs = new MongoGridFS(_context.DataBase); fs.Delete(remoteFile); } catch (Exception ex) { _logger.Error(ex); _logger.Error(ex.StackTrace); throw; } }
public void DeleteDirectory(string virtualPath) { string fixedPath = FixPath(virtualPath); MongoGridFS mongoGridFs = GetGridFS(); var fileInfos = mongoGridFs.Find(Query.Matches("metadata.directory_name", new BsonRegularExpression(new Regex(@"^" + fixedPath)))); foreach (var fi in fileInfos) { mongoGridFs.DeleteById(fi.Id); } mongoGridFs.Delete(fixedPath); if (DirectoryDeleted != null) { DirectoryDeleted.Invoke(this, new FileEventArgs(virtualPath, null)); } }
/// <summary> /// 批量删除文件 /// </summary> /// <param name="files"></param> public void Delete(string[] remoteFiles) { _logger.Debug("Delete Files"); try { MongoGridFS fs = new MongoGridFS(_context.DataBase); foreach (string item in remoteFiles) { fs.Delete(item); } } catch (Exception ex) { _logger.Error(ex); _logger.Error(ex.StackTrace); throw; } }
/// <summary> /// 通过文件名删除文件 /// </summary> /// <param name="fileName">文件名</param> public void DeleteFileByName(string fileName, string pictureDBName) { try { if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(pictureDBName)) { throw new KnownException("缺失必需数据,无法删除数据!"); } MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = pictureDBName }; MongoGridFS fs = new MongoGridFS(_server, _database.Name, fsSetting); fs.Delete(fileName); } catch (Exception ex) { throw ex; } }
private static void Main() { var exit = false; _mongoClient = new MongoClient("mongodb://localhost"); _db = new MongoGridFS(_mongoClient.GetServer(), "Default", new MongoGridFSSettings()); while (!exit) { Console.Write(GetPrepend()); var command = Console.ReadLine(); Debug.Assert(command != null, "command != null"); if (command.Length == 0) { continue; } //What the f**k? //Handles quotation marks in incoming commands var result = command.Split('"') .Select((element, index) => index % 2 == 0 ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : new[] { element }) .SelectMany(element => element).ToList(); switch (result[0].ToLower()) { case "exit": exit = true; break; case "cd": if (result.Count == 2) { if (result[1] == "..") { var sarray = _currentdirectory.Split('/').Where(x => x != "").ToArray(); var str = "/"; for (var i = 0; i < sarray.Length - 1; i++) { str += sarray[i] + "/"; } _currentdirectory = str; } else { _currentdirectory += result[1] + "/"; } } else { Console.WriteLine(" Usage: cd <dir>"); } break; case "server": _mongoClient = new MongoClient("mongodb://" + result[1]); _db = new MongoGridFS(_mongoClient.GetServer(), "Default", new MongoGridFSSettings()); break; case "db": _db = new MongoGridFS(_mongoClient.GetServer(), result[1], new MongoGridFSSettings()); break; case "ls": if (_db != null) { var query = from file in _db.FindAll() where file.Name.StartsWith(_currentdirectory) select file; foreach (var file in query) { Console.WriteLine(" " + file.Name); } } break; case "put": if (result.Count == 2) { var file = new FileInfo(result[1]); if (!file.Exists) { Console.WriteLine(" File doesn't exist!"); break; } Console.Write(" Uploading " + file.Name + "..."); Debug.Assert(_db != null, "_db != null"); _db.Upload(file.FullName, _currentdirectory + file.Name); Console.WriteLine("Done!"); } else if (result.Count == 3) { var file = new FileInfo(result[1]); if (!file.Exists) { Console.WriteLine(" File doesn't exist!"); break; } Console.Write(" Uploading " + file.Name + "..."); Debug.Assert(_db != null, "_db != null"); _db.Upload(file.FullName, result[2]); Console.WriteLine("Done!"); } else { Console.WriteLine(" Usage: put <src> [dest]"); } break; case "get": if (result.Count == 2) { Debug.Assert(_db != null, "_db != null"); if (!_db.Exists(result[1])) { Console.WriteLine(" File doesn't exist!"); break; } Console.Write(" Downloading " + result[1] + "..."); _db.Download(result[1], result[1]); Console.WriteLine("Done!"); } else if (result.Count == 3) { Debug.Assert(_db != null, "_db != null"); if (!_db.Exists(result[1])) { Console.WriteLine(" File doesn't exist!"); break; } Console.Write(" Downloading " + result[1] + "..."); _db.Download(result[2], result[1]); Console.WriteLine("Done!"); } else { Console.WriteLine(" Usage: get <src> [dest]"); } break; case "del": if (result.Count == 2) { Debug.Assert(_db != null, "_db != null"); if (!_db.Exists(result[1])) { Console.WriteLine(" File doesn't exist!"); break; } _db.Delete(result[1]); } else { Console.WriteLine(" Usage: del <filename>"); } break; default: Console.WriteLine(" Invalid Command"); break; } } }
public void TestCopyTo() { _gridFS.Delete(Query.Null); Assert.AreEqual(0, _gridFS.Chunks.Count()); Assert.AreEqual(0, _gridFS.Files.Count()); var contents = "Hello World"; var bytes = Encoding.UTF8.GetBytes(contents); var uploadStream = new MemoryStream(bytes); var createOptions = new MongoGridFSCreateOptions { Aliases = new[] { "HelloWorld", "HelloUniverse" }, ChunkSize = _gridFS.Settings.ChunkSize, ContentType = "text/plain", Id = ObjectId.GenerateNewId(), Metadata = new BsonDocument { { "a", 1 }, { "b", 2 } }, UploadDate = DateTime.UtcNow }; var fileInfo = _gridFS.Upload(uploadStream, "HelloWorld.txt", createOptions); var copyInfo = fileInfo.CopyTo("HelloWorld2.txt"); Assert.AreEqual(2, _gridFS.Chunks.Count()); Assert.AreEqual(2, _gridFS.Files.Count()); Assert.IsNull(copyInfo.Aliases); Assert.AreEqual(fileInfo.ChunkSize, copyInfo.ChunkSize); Assert.AreEqual(fileInfo.ContentType, copyInfo.ContentType); Assert.AreNotEqual(fileInfo.Id, copyInfo.Id); Assert.AreEqual(fileInfo.Length, copyInfo.Length); Assert.AreEqual(fileInfo.MD5, copyInfo.MD5); Assert.AreEqual(fileInfo.Metadata, copyInfo.Metadata); Assert.AreEqual("HelloWorld2.txt", copyInfo.Name); Assert.AreEqual(fileInfo.UploadDate, copyInfo.UploadDate); }
/// <summary> /// 上传文件 /// </summary> /// <remarks>Mongo允许同名文件,因为id才是主键</remarks> /// <param name="strFileName"></param> public static UploadResult UpLoadFile(String strFileName, UpLoadFileOption Option) { MongoDatabase mongoDB = SystemManager.GetCurrentDataBase(); MongoGridFS gfs = mongoDB.GetGridFS(new MongoGridFSSettings()); String RemoteName = String.Empty; if (Option.FileNameOpt == enumGFSFileName.filename) { RemoteName = new FileInfo(strFileName).Name; } else { if (Option.DirectorySeparatorChar != Path.DirectorySeparatorChar) { RemoteName = strFileName.Replace(Path.DirectorySeparatorChar, Option.DirectorySeparatorChar); } else { RemoteName = strFileName; } } try { OnActionDone(new ActionDoneEventArgs(RemoteName + " Uploading ")); if (!gfs.Exists(RemoteName)) { gfs.Upload(strFileName, RemoteName); return(UploadResult.Complete); } else { switch (Option.AlreadyOpt) { case enumGFSAlready.JustAddIt: gfs.Upload(strFileName, RemoteName); return(UploadResult.Complete); case enumGFSAlready.RenameIt: String ExtendName = new FileInfo(strFileName).Extension; String MainName = RemoteName.Substring(0, RemoteName.Length - ExtendName.Length); int i = 1; while (gfs.Exists(MainName + i.ToString() + ExtendName)) { i++; } gfs.Upload(strFileName, MainName + i.ToString() + ExtendName); return(UploadResult.Complete); case enumGFSAlready.SkipIt: return(UploadResult.Skip); case enumGFSAlready.OverwriteIt: gfs.Delete(RemoteName); gfs.Upload(strFileName, RemoteName); return(UploadResult.Complete); case enumGFSAlready.Stop: return(UploadResult.Skip); } return(UploadResult.Skip); } } catch (Exception ex) { SystemManager.ExceptionDeal(ex); return(UploadResult.Exception); } }
/// <summary> /// 删除报表结果 /// </summary> /// <param name="fileName"></param> /// <param name="rootName"></param> public void DeleteFile(string fileName, string rootName) { MongoGridFS fs = GetGridFs(Dbname, rootName); fs.Delete(fileName); }
public void CopyTo() { gridFS.Delete(Query.Null); gridFS.Chunks.Count().Should().Be(0); gridFS.Files.Count().Should().Be(0); var uploadStream = new MemoryStream(ContentBytes); var createOptions = new MongoGridFSCreateOptions { Aliases = new[] { "애국가", "HelloWorld" }, ChunkSize = gridFS.Settings.ChunkSize, ContentType = "text/plain", Id = ObjectId.GenerateNewId(), Metadata = new BsonDocument { { "a", 1 }, { "b", 2 } }, UploadDate = DateTime.UtcNow }; var fileInfo = gridFS.Upload(uploadStream, "HelloWorld.txt", createOptions); fileInfo.Should().Not.Be.Null(); var copyInfo = fileInfo.CopyTo("HelloWorld2.txt"); copyInfo.Should().Not.Be.Null(); gridFS.Chunks.Count().Should().Be(2); // 하나의 파일 크기가 ChunkSize 보다 작으므로 gridFS.Files.Count().Should().Be(2); copyInfo.Aliases.Should().Be.Null(); // Alias는 복사되지 않습니다. copyInfo.ChunkSize.Should().Be(fileInfo.ChunkSize); copyInfo.ContentType.Should().Be(fileInfo.ContentType); copyInfo.Id.Should().Not.Be(fileInfo.Id); copyInfo.Length.Should().Be(fileInfo.Length); copyInfo.MD5.Should().Be(fileInfo.MD5); Assert.AreEqual(fileInfo.Metadata, copyInfo.Metadata); copyInfo.Name.Should().Be("HelloWorld2.txt"); copyInfo.UploadDate.Should().Be(fileInfo.UploadDate); }