public IHttpActionResult DeleteRace(int?id) { if (!id.HasValue) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var raceDB = raceRepository.GetRace(id ?? (int)InvalidPropertyValues.undefinedValue); if (raceDB == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var tickets = ticketRepository.GetTicketsByRace(raceDB.RaceID); if (tickets.Any()) { return(BadRequest("The Race is used in a Ticket!\nTo delete it contact your Database Manager.")); } foreach (var item in raceDB.Assets) { fileManager.DeleteFile(item); filePathRepository.RemoveFilepath(item.FilePath); } fileManager.DeleteFolders(ModelType.Race, raceDB.RaceID.ToString()); raceRepository.Remove(raceDB); unitOfWork.Complete(); return(Ok()); }
public async Task <IActionResult> Edit(ProjectCVM project) { try { var record = _mapper.Map <Project>(project); if (project.BannerPhotoFile != null) { string oldBannerPath = record.BannerPhotoPath; record.BannerPhotoPath = await _fileManager.UploadFile(_appEnvironment.WebRootPath, record.Id.ToString(), project.BannerPhotoFile); if (!string.IsNullOrWhiteSpace(oldBannerPath)) { _fileManager.DeleteFile(_appEnvironment.WebRootPath, oldBannerPath); } } if (project.PreviewPhotoFile != null) { string oldPreviewPath = record.PreviewPhotoPath; record.PreviewPhotoPath = await _fileManager.UploadFile(_appEnvironment.WebRootPath, record.Id.ToString(), project.PreviewPhotoFile); if (!string.IsNullOrWhiteSpace(oldPreviewPath)) { _fileManager.DeleteFile(_appEnvironment.WebRootPath, oldPreviewPath); } } if (project.VideoFile != null) { string oldVideoLink = record.VideoLink; record.VideoLink = await _fileManager.UploadFile(_appEnvironment.WebRootPath, record.Id.ToString(), project.VideoFile); if (!string.IsNullOrWhiteSpace(oldVideoLink)) { _fileManager.DeleteFile(_appEnvironment.WebRootPath, oldVideoLink); } } _db.Projects.Update(record); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(List))); } catch (Exception e) { return(View(project)); } }
public void Delete() { if (SelectedFile != null) { DialogResult confirm = MessageBox.Show("Delete", $"Please confirm deletion of file: {SelectedFile.Name}{SelectedFile.Extension}", MessageBoxButtons.YesNo); if (confirm == DialogResult.Yes) { FM.DeleteFile(SelectedFile.FullName); RefreshFiles(); RefreshCategories(); ChangeCategory(); } } }
public async Task <IActionResult> UploadProfilePhoto(IFormFile uploadedFile) { if (uploadedFile != null) { FileManager _fileManager = new FileManager(_context, _appEnvironment); TeacherProfile profile = await GetCurrentuserAsync(); if (profile != null) { if (profile.PhotoId != null) { _fileManager.DeleteFile(profile.Photo); } File photo = _fileManager.SaveFile(uploadedFile); profile.Photo = photo; _context.TeacherProfiles.Update(profile); _context.SaveChanges(); return(View(nameof(Edit), profile)); } } return(RedirectToAction("Index")); }
internal void DeleteFile_DeletesFolderWhenGroupByFoldersEnabled() { _userSettings.GroupByFoldersEnabled = true; _track.Title = "Delete_Me"; _track.TitleExtended = ""; _userSettings.TrackTitleSeparator = "_"; var artistDir = Regex.Replace(_track.Artist, _windowsExlcudedChars, string.Empty); var outputFile = new OutputFile { Path = $@"{_userSettings.OutputPath}\{artistDir}", File = _track.ToTitleString(), Extension = _userSettings.MediaFormat.ToString().ToLower(), Separator = _userSettings.TrackTitleSeparator }; _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { @"C:\path\Artist", new MockDirectoryData() }, { @"C:\path\Artist\Delete_Me.spytify", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) } }); _fileManager = new FileManager(_userSettings, _track, _fileSystem); _fileManager.DeleteFile(outputFile.ToPendingFileString()); Assert.False(_fileSystem.Directory.Exists($@"{_userSettings.OutputPath}\{artistDir}")); Assert.False(_fileSystem.File.Exists(outputFile.ToPendingFileString())); }
internal void DeleteFile_DeletesFile() { _track.Title = "Delete_Me"; _track.TitleExtended = ""; _userSettings.TrackTitleSeparator = "_"; var outputFile = new OutputFile { Path = _userSettings.OutputPath, File = _track.ToString(), Extension = _userSettings.MediaFormat.ToString().ToLower(), Separator = _userSettings.TrackTitleSeparator }; _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { @"C:\path\Artist_-_Delete_Me.spytify", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) } }); _fileManager = new FileManager(_userSettings, _track, _fileSystem); _fileManager.DeleteFile(outputFile.ToPendingFileString()); Assert.False(_fileSystem.File.Exists(outputFile.ToPendingFileString())); }
public void HasherCalculateFileHash() { FileManager fileManager = new FileManager(); Hasher hasher = new Hasher(); int fileSize = 10000000; string fileName = "TestFile.dat"; try { // Create a test file FileGenerator generator = new FileGenerator(); generator.GenerateRandomBinaryFile(fileName, fileSize); Assert.IsTrue(fileManager.FileExists(fileName)); Assert.IsTrue(fileManager.GetFileInfo(fileName).Length == fileSize); string hash = hasher.HashFile(fileName); byte[] fileBytes = File.ReadAllBytes(fileName); string hashBytes = hasher.Hash(fileBytes); Assert.IsTrue(hash.Equals(hashBytes)); } finally { fileManager.DeleteFile(fileName); } }
public bool RemoveFile(int plannedWorkFileId) { var ok = true; using (var da = new SqlDataAdapter("SELECT * FROM PlannedWorkFiles WHERE PlannedWorkFileID = " + plannedWorkFileId, ConnectionStrings.LightConnectionString)) { using (new SqlCommandBuilder(da)) { using (var dt = new DataTable()) { da.Fill(dt); bool bOk = false; foreach (DataRow Row in dt.Rows) { try { bOk = FM.DeleteFile(Configs.DocumentsPath + FileManager.GetPath("PlannedWorkFiles") + "/" + Row["FileName"].ToString(), Configs.FTPType); } catch { ok = false; return(false); } } if (bOk) { dt.Rows[0].Delete(); da.Update(dt); } } } } return(ok); }
/// <summary> /// 保存md5文件 都更新成功后保存 /// </summary> /// <param name="tabDictionary"></param> private void SaveMD5Table(Dictionary <string, FileInfo> tabDictionary) { string filename = Platform.Path + Platform.Md5FileName; if (FileManager.IsFileExist(filename)) { FileManager.DeleteFile(filename); } string directory = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(directory) && !FileManager.IsDirectoryExist(directory)) { FileManager.CreateDirectory(directory); } try { using (var write = new StreamWriter(new FileStream(filename, FileMode.Create))) { foreach (KeyValuePair <string, FileInfo> keyValuePair in tabDictionary) { write.WriteLine(keyValuePair.Key + "," + keyValuePair.Value.md5 + "," + keyValuePair.Value.size); } } } catch (Exception e) { Debuger.LogError(e.Message); } }
/// <summary> /// 删除没用的文件 /// </summary> private void DeleteUselessFiles() { if (newmd5Table.Count == 0) { return; } List <string> deleteFiles = new List <string>(); foreach (KeyValuePair <string, FileInfo> keyValuePair in oldmd5Table) { if (newmd5Table.ContainsKey(keyValuePair.Key)) { continue; } deleteFiles.Add(keyValuePair.Key); //删除沙河目录下的没用文件 oldmd5Table.Remove(keyValuePair.Key); } foreach (string deleteFile in deleteFiles) { string filename = Platform.Path + deleteFile; if (FileManager.IsFileExist(filename)) { FileManager.DeleteFile(filename); } } }
public IActionResult DeleteProduct(int Id) { string nvm; try { var entity = dbProductAbstract.FindById(Id); if (entity != null) { var ProductImageFiles = _db.ProductImage.Where(x => x.ProductId == entity.Id).ToList(); var ProductAbstractDeleted = dbProductAbstract.DeleteById(Id); if (true) { if (ProductImageFiles.Count > 0) { foreach (var item in ProductImageFiles) { //delete related image files: bool imgDel = FileManager.DeleteFile(contentRootPath, item.ImagePath); bool thumbnailImgDel = FileManager.DeleteFile(contentRootPath, item.ImageThumbnailPath); } bool dirDel = FileManager.DeleteDirectory(contentRootPath, ProductImageFiles.FirstOrDefault().ImagePath); } nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Success_Remove, contentRootPath); return(Json(nvm)); } } } catch (Exception) { } nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Remove, contentRootPath); return(Json(nvm)); }
public IActionResult DeleteCategory(int Id) { string nvm; var entity = dbCategory.FindById(Id); if (entity != null) { try { bool status = dbCategory.DeleteById(Id); dbCategory.Save(); if (status) { if (entity.ImagePath != null) { bool imgDel = FileManager.DeleteFile(contentRootPath, entity.ImagePath); } nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Success_Remove, contentRootPath); return(Json(nvm)); } } catch (Exception) { nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Remove, contentRootPath); return(Json(nvm)); } } nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Operation, contentRootPath); return(Json(nvm)); }
public static bool WriteFile(string filePath, byte[] data) { int num = 0; bool result; while (true) { try { //File.WriteAllBytes(filePath, data); result = true; break; } catch (Exception ex) { num++; if (num >= 3) { Debug.Log("Write File " + filePath + " Error! Exception = " + ex.ToString()); FileManager.DeleteFile(filePath); FileManager.s_delegateOnOperateFileFail(filePath, enFileOperation.WriteFile); result = false; break; } } } return(result); }
public static bool WriteFile(string filePath, byte[] data, int offset, int length) { FileStream fileStream = null; int num = 0; bool result; while (true) { try { fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); fileStream.Write(data, offset, length); fileStream.Close(); result = true; break; } catch (Exception ex) { if (fileStream != null) { fileStream.Close(); } num++; if (num >= 3) { Debug.Log("Write File " + filePath + " Error! Exception = " + ex.ToString()); FileManager.DeleteFile(filePath); FileManager.s_delegateOnOperateFileFail(filePath, enFileOperation.WriteFile); result = false; break; } } } return(result); }
/// <summary> /// 保存设计报表 /// </summary> /// <param name="reportID"></param> /// <param name="reportUUID"></param> /// <returns></returns> public ActionResult SaveDesignedReport(string reportID, string reportUUID) { ITopClient client = new TopClientDefault(); Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("CompanyID", this.CompanyID); dic.Add("SnNum", reportID); if (reportID.IsEmpty()) { return(Redirect("/Report/Manager/List")); } string result = client.Execute(ReportApiName.ReportApiName_GetSingle, dic); DataResult <ReportsEntity> dataResult = JsonConvert.DeserializeObject <DataResult <ReportsEntity> >(result); ReportsEntity entity = dataResult.Result; if (entity.IsNull()) { return(Redirect("/Report/Manager/List")); } string FileRealPath = Server.MapPath("~" + entity.FileName); string FileTempPath = Server.MapPath("~/Theme/content/report/temp/" + reportUUID); FileManager.DeleteFile(FileRealPath); System.IO.File.Copy(FileTempPath, FileRealPath, true); return(Content("")); }
public ActionResult Index(HttpPostedFileBase file) { var userId = User.Identity.GetUserId(); var user = UserManager.GetUser(userId); string currentImagePath = UserManager.GetUserImagePath(userId); bool success = false; string imagePath = string.Empty; if (file != null && file.ContentLength > 0) { imagePath = new FileManager().Save(file); if (String.IsNullOrWhiteSpace(imagePath)) { return(RedirectToAction("Index", new { Message = ManageMessageId.AvatarFormatError })); } if (String.IsNullOrEmpty(currentImagePath) == false) { FileManager fileManager = new FileManager(); fileManager.DeleteFile(currentImagePath); } success = UserManager.ChangeUserAvatar(User.Identity.GetUserId(), imagePath); } if (success) { return(RedirectToAction("Index", new { Message = ManageMessageId.AvatarChangeSuccess })); } //Error! return(View()); }
void CustomInitialize() { SpriteSave spriteSave = new SpriteSave(); spriteSave.X = 4; FileManager.InitializeUserFolder("Global"); string directory = FileManager.GetUserFolder("Global"); string fileName = directory + "TestSave.xml"; FileManager.XmlSerialize(spriteSave, fileName); if (FileManager.FileExists(fileName) == false) { throw new Exception("The file " + fileName + " does not exist"); } var loaded = FileManager.XmlDeserialize <SpriteSave>(fileName); if (loaded.X != 4) { throw new Exception("XML serialization is not working properly"); } string fileToAddAndDelete = directory + "DeleteMe.xml"; FileManager.XmlSerialize <SpriteSave>(spriteSave, fileName); FileManager.DeleteFile(fileName); }
/// <summary> /// Редактирование слайда /// </summary> /// <param name="model"></param> /// <returns></returns> public BaseResponse <int> EditSlide(SliderEditModel model) { try { using (var db = new DataContext()) { var old = db.Sliders.FirstOrDefault(x => x.Id == model.Id); if (old == null) { return(new BaseResponse <int>(EnumResponseStatus.Error, "Слайд не найден")); } old.IsActive = model.IsActive; if (model.PhotoFile != null) { FileManager.DeleteFile(EnumDirectoryType.Slider, fileName: old.PhotoUrl); old.PhotoUrl = FileManager.SaveImage(model.PhotoFile, EnumDirectoryType.Slider, Guid.NewGuid().ToString()); } db.SaveChanges(); return(new BaseResponse <int>(EnumResponseStatus.Success, "Слайд успешно изменен", old.Id)); } } catch (Exception ex) { return(new BaseResponse <int>(EnumResponseStatus.Exception, ex.Message)); } }
private async void btnDelete_Clicked(object sender, EventArgs e) { try { List <ImageInfo> listImages = new List <ImageInfo>(); if (Selected >= 1) { listImages = TrashImages.Where(x => x.Selected == true).ToList <ImageInfo>(); } else { listImages = TrashImages.ToList <ImageInfo>(); } bool answer = await DeleteConfirmNotifications(listImages.Count); if (answer) { foreach (ImageInfo _image in listImages) { FileManager.DeleteFile(_image.ImagePath); } await LoadBitmapCollection(); ShowToastMessage("Photos deleted permanently!"); } } catch (Exception ex) { await DisplayAlert("Error", "An error has ocurred: " + ex.Message, "OK"); } }
static void Main(string[] args) { string[] testLines = { "12 + 23", "23*34", "34-45", "45/56" }; string[] testLines1 = { "56+67", "67*78", "", "89/90" }; FileManager fm = new FileManager(); Console.WriteLine(FormatArray(fm.FileNames)); fm.NewFile("Jonas.jk").WriteFileContents(testLines); fm.NewFile("Krook.jk").WriteFileContents(testLines); fm.NewFile("Add.jk").WriteFileContents(testLines); fm.NewFile("Exp.jk").WriteFileContents(testLines); fm.NewFile("Trigonometry.jk").WriteFileContents(testLines); Console.WriteLine(FormatArray(fm.FileNames)); fm.ChangeFile(2); Console.WriteLine(FormatArray(fm.FileNames)); fm.DeleteFile(0); Console.WriteLine(FormatArray(fm.FileNames)); fm.ChangeFile(1).WriteFileContents(testLines1); Console.WriteLine(fm.ChangeFile(1).ReadFileContents()); Console.WriteLine(fm.ChangeFile(1)); Console.Read(); fm.DeleteAllFiles(); }
internal void DeleteFile_DeletesNetworkFileAndFolderWhenGroupByFoldersEnabled() { _userSettings.GroupByFoldersEnabled = true; _userSettings.OutputPath = NETWORK_PATH; _userSettings.MediaFormat = MediaFormat.Mp3; _track.Title = "Delete_Me"; _track.TitleExtended = ""; _userSettings.TrackTitleSeparator = "_"; _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { $@"{NETWORK_PATH}\Artist", new MockDirectoryData() }, { $@"{NETWORK_PATH}\Artist\Single", new MockDirectoryData() }, { $@"{NETWORK_PATH}\Artist\Single\Delete_Me.mp3", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) } }); _fileManager = new FileManager(_userSettings, _track, _fileSystem, DateTime.Now); var outputFile = _fileManager.GetOutputFile(); Assert.True(_fileSystem.File.Exists(outputFile.ToMediaFilePath())); _fileManager.DeleteFile(outputFile.ToMediaFilePath()); Assert.False(_fileSystem.Directory.Exists($@"{NETWORK_PATH}\Artist")); Assert.False(_fileSystem.Directory.Exists($@"{NETWORK_PATH}\Artist\Single")); Assert.False(_fileSystem.Directory.Exists($@"{NETWORK_PATH}\{_tempFileFullPath}")); Assert.False(_fileSystem.File.Exists(outputFile.ToMediaFilePath())); }
internal void DeleteFile_WithInvalidFileName_Throws() { _track.Title = "Delete Me"; _track.TitleExtended = ""; _track.Artist = null; _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { $@"{PATH}\Artist", new MockDirectoryData() }, { $@"{PATH}\Artist\Single", new MockDirectoryData() }, { $@"{PATH}\Artist\Single\Delete Me.mp3", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) } }); var outputFile = new OutputFile { FoldersPath = _userSettings.OutputPath, MediaFile = _track.ToString(), Extension = _userSettings.MediaFormat.ToString().ToLower(), Separator = _userSettings.TrackTitleSeparator }; var ex = Assert.Throws <Exception>(() => _fileManager.DeleteFile(outputFile.ToMediaFilePath())); Assert.Equal("File name cannot be null.", ex.Message); }
public void Take() { var fileName = System.DateTime.Now.ToString("Cap_yyyy-MM-dd_HH.mm.ss") + ".png"; var filePath = Application.persistentDataPath + "/" + fileName; Debug.Log(filePath); Observable .FromCoroutine(_ => Screenshot(fileName, filePath)) .Timeout(System.TimeSpan.FromSeconds(5)) .Subscribe( _ => { _twitterManager.FilePath = filePath; _twitterManager.startLogin(); _uICanvas.enabled = true; }, ex => { Debug.Log("Login Failed: " + ex.Message); #if UNITY_EDITOR filePath = _fileManager.GetProjectDirectoryPath() + "/" + fileName; #endif _fileManager.DeleteFile(filePath); _uICanvas.enabled = true; } ).AddTo(this); }
public static void Main() { FileManager newfile = new FileManager(); // Create a new directory newfile.FilePath = @"files/file-folder"; // directory name newfile.CreateDirectory(); // Write file in newly created directory newfile.FilePath = @"files/file-folder/another.txt"; // directory and file name newfile.CreateAndWriteFile(); // Read from the newly created file newfile.FilePath = @"files/file-folder/another.txt"; newfile.ReadFromFile(); // Copy to new directory string source = @"files/file-folder"; string destination = @"files/another-folder"; newfile.CopyToAnotherDirectory(source, destination, "another.txt"); // Delete file newfile.FilePath = @"files/file-folder/another.txt"; newfile.DeleteFile(); // Delete directory newfile.FilePath = @"files/file-folder"; newfile.DeleteDirectory(); }
internal void DeleteFile_WithUnixFormattedPath_DeletesFile() { _track.Title = "Delete Me"; _track.TitleExtended = ""; _track.Album = null; _userSettings.GroupByFoldersEnabled = true; _userSettings.TrackTitleSeparator = " "; _userSettings.OutputPath = NETWORK_PATH; _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { $@"{NETWORK_PATH}\Artist", new MockDirectoryData() }, { $@"{NETWORK_PATH}\Artist\Untitled", new MockDirectoryData() }, { $@"{NETWORK_PATH}\Artist\Untitled\Delete Me.mp3", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) } }); _fileManager = new FileManager(_userSettings, _track, _fileSystem, DateTime.Now); var outputFile = _fileManager.GetOutputFile(); Assert.True(_fileSystem.File.Exists(outputFile.ToMediaFilePath())); _fileManager.DeleteFile(outputFile.ToMediaFilePath()); Assert.False(_fileSystem.File.Exists(outputFile.ToMediaFilePath())); }
private void CreateFed(string directory) { fed = new FrontEndData(); fed.LibraryPath = directory; string[] files = Directory.GetFiles(directory); foreach (string f in files) { var ext = Path.GetExtension(f); if (ext == ".gb" || ext == ".gbc") { var game = new Game(); game.Name = Path.GetFileName(f); game.FilePath = "\"" + f + "\""; fed.Games.Add(game); } } FileManager.DeleteFile("FED.dat"); FileManager.CreateFile("FED.dat"); using (StreamWriter sw = new StreamWriter(FileManager.GetWriteStream("FED.dat"))) { sw.Write(JsonConvert.SerializeObject(fed)); } }
public static void DiffFile() { string basePath = Application.dataPath + "/../"; string oldFile = basePath + "Diff/old" + ext; string newFile = basePath + "Diff/new" + ext; string patchFile = basePath + "Diff/patch"; if (File.Exists(oldFile) == false || File.Exists(newFile) == false) { Debug.Log("cant find file oldFile=" + oldFile + ";newFile=" + newFile); return; } FileManager.DeleteFile(patchFile); string[] list = new string[4]; list[0] = "bsdiff"; list[1] = oldFile; list[2] = newFile; list[3] = patchFile; Debug.Log("oldFile ===" + oldFile); Debug.Log("newFile ===" + newFile); Debug.Log("patchFile ===" + patchFile); int value = DllManager.StartDiff(oldFile, newFile, patchFile); Debug.Log("DiffFile ===" + value); }
/// <summary> 清理本地AB包和版本XML文件 </summary> private void DeleteLocalVersionXml() { if (FileManager.FileExist(XmlLocalVersionPath)) { FileManager.DeleteFile(XmlLocalVersionPath); FileManager.DeleteFolder(LocalPath); } }
public void File_Does_Not_Exists_For_Deletion() { var path = @"C:\files\toDelete.txt"; var mockFileSystem = new MockFileSystem(); var sut = new FileManager(mockFileSystem); Assert.That(() => sut.DeleteFile(path), Throws.TypeOf <ArgumentException>()); }
public void File_Path_Is_Null_For_Deletion() { string path = null; var mockFileSystem = new MockFileSystem(); var sut = new FileManager(mockFileSystem); Assert.That(() => sut.DeleteFile(path), Throws.TypeOf <ArgumentNullException>()); }