/// <summary> /// Makes the backup. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="twoBackups">if set to <c>true</c> [two backups].</param> public static void DeleteWithBackup(string fileName, bool twoBackups) { Contract.Requires(fileName != null); try { if (!FileExists(fileName)) { return; } var backupName = fileName + ".bak"; var backupName2 = fileName + "2.bak"; if (twoBackups) { FileDelete(backupName2); } if (FileExists(backupName)) { if (twoBackups) { File.Move(backupName, backupName2); } FileDelete(backupName); } File.Move(fileName, backupName); } catch { // ignored } }
public override async Task <FileSystemResult> MoveAsync(IDirectory destination) { try { DirectoryImplementation to = destination as DirectoryImplementation; if (to == null) { return(new FileSystemResult("Destination should be a Local Directory")); } if (to is LocalRoot) { return(new FileSystemResult("Root cannot be destination")); } string destname = Path.Combine(to.FullName, Name); File.Move(FullName, destname); ((DirectoryImplementation)Parent).IntFiles.Remove(this); to.IntFiles.Add(this); this.Parent = to; file = new FileInfo(destname); return(await Task.FromResult(new FileSystemResult())); } catch (Exception e) { return(new FileSystemResult(e.Message)); } }
public void Move(string fromPath, string toPath) { var name = toPath.Split('\\').Last(); ValidateNameLength(name); File.Move(fromPath, toPath); }
public void TestCopy() { var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("file22.ext").ToString(); var tempDestLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("file22-1.ext").ToString(); Assert.IsFalse(File.Exists(tempLongPathFilename)); File.Copy(longPathFilename, tempLongPathFilename); try { Assert.IsTrue(File.Exists(tempLongPathFilename)); File.Move(tempLongPathFilename, tempDestLongPathFilename); try { Assert.IsFalse(File.Exists(tempLongPathFilename)); Assert.IsTrue(File.Exists(tempDestLongPathFilename)); } finally { File.Delete(tempDestLongPathFilename); } } finally { if (File.Exists(tempLongPathFilename)) { File.Delete(tempLongPathFilename); } } }
public void RenameFile(string renameScript) { string renamed = RenameFileHelper.GetNewFileName(this, renameScript); if (string.IsNullOrEmpty(renamed)) { return; } ImportFolderRepository repFolders = new ImportFolderRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); // actually rename the file string fullFileName = this.FullServerPath; // check if the file exists if (!File.Exists(fullFileName)) { logger.Error("Error could not find the original file for renaming: " + fullFileName); return; } // actually rename the file string path = Path.GetDirectoryName(fullFileName); string newFullName = Path.Combine(path, renamed); try { logger.Info(string.Format("Renaming file From ({0}) to ({1})....", fullFileName, newFullName)); if (fullFileName.Equals(newFullName, StringComparison.InvariantCultureIgnoreCase)) { logger.Info(string.Format("Renaming file SKIPPED, no change From ({0}) to ({1})", fullFileName, newFullName)); } else { File.Move(fullFileName, newFullName); logger.Info(string.Format("Renaming file SUCCESS From ({0}) to ({1})", fullFileName, newFullName)); string newPartialPath = ""; int folderID = this.ImportFolderID; DataAccessHelper.GetShareAndPath(newFullName, repFolders.GetAll(), ref folderID, ref newPartialPath); this.FilePath = newPartialPath; repVids.Save(this, true); } } catch (Exception ex) { logger.Info(string.Format("Renaming file FAIL From ({0}) to ({1}) - {2}", fullFileName, newFullName, ex.Message)); logger.ErrorException(ex.ToString(), ex); } }
public static void MoveWithReplace(string sourceFileName, string destFileName) { //first, delete target file if exists, as File.Move() does not support overwrite if (File.Exists(destFileName)) { File.Delete(destFileName); } File.Move(sourceFileName, destFileName); }
public static void FixLibraryFolders() { var folders = Directory.EnumerateDirectories(Paths.OutputPath, "*", SearchOption.TopDirectoryOnly); foreach (var folder in folders) { var name = Path.GetFileName(folder); var oldName = name; name = Regex.Replace(name, @"\b(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY|AU|MATRiX|DVDR|WAV|AiR|ArCADE|VR|CDDA|PAD|MiDi|CoBaLT|DiSCOVER)\b", ""); name = Regex.Replace(name, @"\b(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK|MAGNETRiXX|TZ7iSO|KLI|DVDriSO|DVD9|KRock|ACiD|REX|RMX|SynthX|AiFF|Apple Loops|AiRISO|MULTiFORMAT|AudioP2P|GHOSTiSO|REX2|DXi|HYBRiD|AKAI|ALFiSO)\b", "", RegexOptions.IgnoreCase); name = Regex.Replace(name, @" +", " "); if (name != oldName && !Directory.Exists(Path.GetDirectoryName(folder) + @"\" + name)) { File.Move(folder, Path.GetDirectoryName(folder) + @"\" + name); } } }
public override async Task <FileSystemResult> RenameAsync(string newname) { try { if (string.Equals(Name, newname)) { return(new FileSystemResult("Unable to rename, names are the same")); } string newfullname = Path.Combine(Parent.FullName, newname); File.Move(FullName, newfullname); FileInfo finfo = new FileInfo(newfullname); file = finfo; return(await Task.FromResult(new FileSystemResult())); } catch (Exception e) { return(new FileSystemResult(e.Message)); } }
public void TestMove() { string sourceFilename = Util.CreateNewFile(longPathDirectory); string destFilename = Path.Combine(longPathDirectory, Path.GetRandomFileName()); File.Move(sourceFilename, destFilename); try { Assert.IsFalse(File.Exists(sourceFilename)); Assert.IsTrue(File.Exists(destFilename)); Assert.IsTrue(Util.VerifyContentsOfNewFile(destFilename)); } finally { if (File.Exists(destFilename)) { File.Delete(destFilename); } } }
static void CopyFiles(string source, string dest, bool move, bool includeArchives = true) { if (move) { MarkFolderWritable(source); } MarkFolderWritable(dest); Console.WriteLine("{0} {1} => {2}", move ? "Moving" : "Copying", source, dest); source = source.TrimEnd('\\'); dest = dest.TrimEnd('\\'); if (!Directory.Exists(dest)) { Directory.CreateDirectory(dest); } Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories).Select(d => d.Replace(source, dest)).ForEach(path => Directory.CreateDirectory(path)); foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories).Where(f => Path.GetExtension(f) != ".nfo" && !Regex.IsMatch(Path.GetFileName(f), "All.Collection.Upload|WareZ-Audio", RegexOptions.IgnoreCase)).ToArray()) { if (Path.GetExtension(file) == ".sfv") { continue; } //if (!includeArchives && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip|iso)")) if (!includeArchives && Path.GetDirectoryName(file) == source && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip)")) { continue; } var newFile = file.Replace(source, dest); if (move) { if (File.Exists(newFile)) { File.Delete(newFile); } File.Move(file, newFile); } else { File.Copy(file, newFile, true); } } }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_DownloadImage: {0}", EntityID); string downloadURL = string.Empty; try { ImageDownloadRequest req = null; switch (EntityTypeEnum) { case ImageEntityType.TvDB_Episode: TvDB_Episode ep = RepoFactory.TvDB_Episode.GetByID(EntityID); if (string.IsNullOrEmpty(ep?.Filename)) { logger.Warn($"TvDB Episode image failed to download: Can't get episode with ID: {EntityID}"); return; } req = new ImageDownloadRequest(EntityTypeEnum, ep, ForceDownload); break; case ImageEntityType.TvDB_FanArt: TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(EntityID); if (string.IsNullOrEmpty(fanart?.BannerPath)) { logger.Warn($"TvDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}"); RemoveImageRecord(); return; } req = new ImageDownloadRequest(EntityTypeEnum, fanart, ForceDownload); break; case ImageEntityType.TvDB_Cover: TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(EntityID); if (string.IsNullOrEmpty(poster?.BannerPath)) { logger.Warn($"TvDB Poster image failed to download: Can't find valid poster with ID: {EntityID}"); RemoveImageRecord(); return; } req = new ImageDownloadRequest(EntityTypeEnum, poster, ForceDownload); break; case ImageEntityType.TvDB_Banner: TvDB_ImageWideBanner wideBanner = RepoFactory.TvDB_ImageWideBanner.GetByID(EntityID); if (string.IsNullOrEmpty(wideBanner?.BannerPath)) { logger.Warn($"TvDB Banner image failed to download: Can't find valid banner with ID: {EntityID}"); RemoveImageRecord(); return; } req = new ImageDownloadRequest(EntityTypeEnum, wideBanner, ForceDownload); break; case ImageEntityType.MovieDB_Poster: MovieDB_Poster moviePoster = RepoFactory.MovieDB_Poster.GetByID(EntityID); if (string.IsNullOrEmpty(moviePoster?.URL)) { logger.Warn($"MovieDB Poster image failed to download: Can't find valid poster with ID: {EntityID}"); RemoveImageRecord(); return; } req = new ImageDownloadRequest(EntityTypeEnum, moviePoster, ForceDownload); break; case ImageEntityType.MovieDB_FanArt: MovieDB_Fanart movieFanart = RepoFactory.MovieDB_Fanart.GetByID(EntityID); if (string.IsNullOrEmpty(movieFanart?.URL)) { logger.Warn($"MovieDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}"); return; } req = new ImageDownloadRequest(EntityTypeEnum, movieFanart, ForceDownload); break; case ImageEntityType.AniDB_Cover: SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(EntityID); if (anime == null) { logger.Warn($"AniDB poster image failed to download: Can't find AniDB_Anime with ID: {EntityID}"); return; } AniDbImageRateLimiter.Instance.EnsureRate(); req = new ImageDownloadRequest(EntityTypeEnum, anime, ForceDownload); break; case ImageEntityType.AniDB_Character: AniDB_Character chr = RepoFactory.AniDB_Character.GetByCharID(EntityID); if (chr == null) { logger.Warn($"AniDB Character image failed to download: Can't find AniDB Character with ID: {EntityID}"); return; } AniDbImageRateLimiter.Instance.EnsureRate(); req = new ImageDownloadRequest(EntityTypeEnum, chr, ForceDownload); break; case ImageEntityType.AniDB_Creator: AniDB_Seiyuu creator = RepoFactory.AniDB_Seiyuu.GetBySeiyuuID(EntityID); if (creator == null) { logger.Warn($"AniDB Seiyuu image failed to download: Can't find Seiyuu with ID: {EntityID}"); return; } AniDbImageRateLimiter.Instance.EnsureRate(); req = new ImageDownloadRequest(EntityTypeEnum, creator, ForceDownload); break; } if (req == null) { logger.Warn($"Image failed to download: No implementation found for {EntityTypeEnum}"); return; } List <string> fileNames = new List <string>(); List <string> downloadURLs = new List <string>(); string fileNameTemp = GetFileName(req, false); string downloadURLTemp = GetFileURL(req, false); fileNames.Add(fileNameTemp); downloadURLs.Add(downloadURLTemp); if (req.ImageType == ImageEntityType.TvDB_FanArt) { fileNameTemp = GetFileName(req, true); downloadURLTemp = GetFileURL(req, true); fileNames.Add(fileNameTemp); downloadURLs.Add(downloadURLTemp); } for (int i = 0; i < fileNames.Count; i++) { try { string fileName = fileNames[i]; downloadURL = downloadURLs[i]; bool downloadImage = true; bool fileExists = File.Exists(fileName); bool imageValid = fileExists && Misc.IsImageValid(fileName); if (imageValid && !req.ForceDownload) { downloadImage = false; } if (!downloadImage) { continue; } string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(), Path.GetFileName(fileName)); try { if (fileExists) { File.Delete(fileName); } } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture); logger.Warn(Resources.Command_DeleteError, fileName, ex.Message); return; } // If this has any issues, it will throw an exception, so the catch below will handle it RecursivelyRetryDownload(downloadURL, ref tempName, 0, 5); // move the file to it's final location // check that the final folder exists string fullPath = Path.GetDirectoryName(fileName); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } File.Move(tempName, fileName); logger.Info($"Image downloaded: {fileName} from {downloadURL}"); } catch (WebException e) { logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL, EntityID, e.Message); // Remove the record if the image doesn't exist or can't download RemoveImageRecord(); } } } catch (Exception ex) { logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL, EntityID, ex.Message); } }
public static void Move(string sourcePath, string destinationPath) { File.Move(sourcePath, destinationPath); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_DownloadAniDBImages: {0}", AnimeID); AniDbRateLimiter.Instance.EnsureRate(); try { List <ImageEntityType> types = new List <ImageEntityType> { ImageEntityType.AniDB_Cover, ImageEntityType.AniDB_Character, ImageEntityType.AniDB_Creator }; foreach (var EntityTypeEnum in types) { List <string> downloadURLs = new List <string>(); List <string> fileNames = new List <string>(); switch (EntityTypeEnum) { case ImageEntityType.AniDB_Cover: SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(AnimeID); if (anime == null) { logger.Warn( $"AniDB poster image failed to download: Can't find AniDB_Anime with ID: {AnimeID}"); return; } downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, anime.Picname)); fileNames.Add(anime.PosterPath); break; case ImageEntityType.AniDB_Character: if (!ServerSettings.AniDB_DownloadCharacters) { continue; } var chrs = (from xref1 in RepoFactory.AniDB_Anime_Character.GetByAnimeID(AnimeID) select RepoFactory.AniDB_Character.GetByCharID(xref1.CharID)) .Where(a => !string.IsNullOrEmpty(a?.PicName)) .DistinctBy(a => a.CharID) .ToList(); if (chrs == null || chrs.Count == 0) { logger.Warn( $"AniDB Character image failed to download: Can't find Character for anime: {AnimeID}"); return; } foreach (var chr in chrs) { downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, chr.PicName)); fileNames.Add(chr.GetPosterPath()); } ShokoService.CmdProcessorGeneral.QueueState = PrettyDescriptionCharacters; break; case ImageEntityType.AniDB_Creator: if (!ServerSettings.AniDB_DownloadCreators) { continue; } var creators = (from xref1 in RepoFactory.AniDB_Anime_Character.GetByAnimeID(AnimeID) from xref2 in RepoFactory.AniDB_Character_Seiyuu.GetByCharID(xref1.CharID) select RepoFactory.AniDB_Seiyuu.GetBySeiyuuID(xref2.SeiyuuID)) .Where(a => !string.IsNullOrEmpty(a?.PicName)) .DistinctBy(a => a.SeiyuuID) .ToList(); if (creators == null || creators.Count == 0) { logger.Warn( $"AniDB Seiyuu image failed to download: Can't find Seiyuus for anime: {AnimeID}"); return; } foreach (var creator in creators) { downloadURLs.Add(string.Format(Constants.URLS.AniDB_Images, creator.PicName)); fileNames.Add(creator.GetPosterPath()); } ShokoService.CmdProcessorGeneral.QueueState = PrettyDescriptionCreators; break; } if (downloadURLs.Count == 0 || fileNames.All(a => string.IsNullOrEmpty(a))) { logger.Warn("Image failed to download: No URLs were generated. This should never happen"); return; } for (int i = 0; i < downloadURLs.Count; i++) { try { if (string.IsNullOrEmpty(fileNames[i])) { continue; } bool downloadImage = true; bool fileExists = File.Exists(fileNames[i]); bool imageValid = fileExists && Misc.IsImageValid(fileNames[i]); if (imageValid && !ForceDownload) { downloadImage = false; } if (!downloadImage) { continue; } string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(), Path.GetFileName(fileNames[i])); try { if (fileExists) { File.Delete(fileNames[i]); } } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture); logger.Warn(Resources.Command_DeleteError, fileNames, ex.Message); return; } // If this has any issues, it will throw an exception, so the catch below will handle it RecursivelyRetryDownload(downloadURLs[i], ref tempName, 0, 5); // move the file to it's final location // check that the final folder exists string fullPath = Path.GetDirectoryName(fileNames[i]); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } File.Move(tempName, fileNames[i]); logger.Info($"Image downloaded: {fileNames[i]} from {downloadURLs[i]}"); } catch (WebException e) { logger.Warn("Error processing CommandRequest_DownloadAniDBImages: {0} ({1}) - {2}", downloadURLs[i], AnimeID, e.Message); }catch (Exception e) { logger.Error("Error processing CommandRequest_DownloadAniDBImages: {0} ({1}) - {2}", downloadURLs[i], AnimeID, e); } } } } catch (Exception ex) { logger.Error("Error processing CommandRequest_DownloadAniDBImages: {0} - {1}", AnimeID, ex); } AniDbRateLimiter.Instance.ResetRate(); }
public void MoveFileIfRequired() { try { logger.Trace("Attempting to move file: {0}", this.FullServerPath); // check if this file is in the drop folder // otherwise we don't need to move it if (this.ImportFolder.IsDropSource == 0) { logger.Trace("Not moving file as it is NOT in the drop folder: {0}", this.FullServerPath); return; } if (!File.Exists(this.FullServerPath)) { logger.Error("Could not find the file to move: {0}", this.FullServerPath); return; } // find the default destination ImportFolder destFolder = null; ImportFolderRepository repFolders = new ImportFolderRepository(); foreach (ImportFolder fldr in repFolders.GetAll()) { if (fldr.IsDropDestination == 1) { destFolder = fldr; break; } } if (destFolder == null) { return; } if (!System.IO.Directory.Exists(destFolder.ImportFolderLocation)) { return; } // keep the original drop folder for later (take a copy, not a reference) ImportFolder dropFolder = this.ImportFolder; // we can only move the file if it has an anime associated with it List <CrossRef_File_Episode> xrefs = this.EpisodeCrossRefs; if (xrefs.Count == 0) { return; } CrossRef_File_Episode xref = xrefs[0]; // find the series associated with this episode AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByAnimeID(xref.AnimeID); if (series == null) { return; } // find where the other files are stored for this series // if there are no other files except for this one, it means we need to create a new location bool foundLocation = false; string newFullPath = ""; // sort the episodes by air date, so that we will move the file to the location of the latest episode List <AnimeEpisode> allEps = series.GetAnimeEpisodes().OrderByDescending(a => a.AniDB_EpisodeID).ToList(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); CrossRef_File_EpisodeRepository repFileEpXref = new CrossRef_File_EpisodeRepository(); foreach (AnimeEpisode ep in allEps) { // check if this episode belongs to more than one anime // if it does we will ignore it List <CrossRef_File_Episode> fileEpXrefs = repFileEpXref.GetByEpisodeID(ep.AniDB_EpisodeID); int? animeID = null; bool crossOver = false; foreach (CrossRef_File_Episode fileEpXref in fileEpXrefs) { if (!animeID.HasValue) { animeID = fileEpXref.AnimeID; } else { if (animeID.Value != fileEpXref.AnimeID) { crossOver = true; } } } if (crossOver) { continue; } foreach (VideoLocal vid in ep.GetVideoLocals()) { if (vid.VideoLocalID != this.VideoLocalID) { // make sure this folder is not the drop source if (vid.ImportFolder.IsDropSource == 1) { continue; } string thisFileName = vid.FullServerPath; string folderName = Path.GetDirectoryName(thisFileName); if (Directory.Exists(folderName)) { newFullPath = folderName; foundLocation = true; break; } } } if (foundLocation) { break; } } if (!foundLocation) { // we need to create a new folder string newFolderName = Utils.RemoveInvalidFolderNameCharacters(series.GetAnime().PreferredTitle); newFullPath = Path.Combine(destFolder.ImportFolderLocation, newFolderName); if (!Directory.Exists(newFullPath)) { Directory.CreateDirectory(newFullPath); } } int newFolderID = 0; string newPartialPath = ""; string newFullServerPath = Path.Combine(newFullPath, Path.GetFileName(this.FullServerPath)); DataAccessHelper.GetShareAndPath(newFullServerPath, repFolders.GetAll(), ref newFolderID, ref newPartialPath); logger.Info("Moving file from {0} to {1}", this.FullServerPath, newFullServerPath); if (File.Exists(newFullServerPath)) { logger.Trace( "Not moving file as it already exists at the new location, deleting source file instead: {0} --- {1}", this.FullServerPath, newFullServerPath); // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(this.FullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this, true); } else { string originalFileName = this.FullServerPath; FileInfo fi = new FileInfo(originalFileName); // now move the file File.Move(this.FullServerPath, newFullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this, true); try { // move any subtitle files foreach (string subtitleFile in Utils.GetPossibleSubtitleFiles(originalFileName)) { if (File.Exists(subtitleFile)) { FileInfo fiSub = new FileInfo(subtitleFile); string newSubPath = Path.Combine(Path.GetDirectoryName(newFullServerPath), fiSub.Name); if (File.Exists(newSubPath)) { // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(newSubPath); } else { File.Move(subtitleFile, newSubPath); } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } // check for any empty folders in drop folder // only for the drop folder if (dropFolder.IsDropSource == 1) { foreach ( string folderName in Directory.GetDirectories(dropFolder.ImportFolderLocation, "*", SearchOption.AllDirectories)) { if (Directory.Exists(folderName)) { if (Directory.GetFiles(folderName, "*", SearchOption.AllDirectories).Length == 0) { try { Directory.Delete(folderName, true); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } } } } } } catch (Exception ex) { string msg = string.Format("Could not move file: {0} -- {1}", this.FullServerPath, ex.ToString()); logger.ErrorException(msg, ex); } }