public async Task <IActionResult> Edit(Guid id, Audio audio) { try { if (id != audio.ID) { return(BadRequest()); } var list = await AddOns.ReadFromJson(); var solo = list.FirstOrDefault(x => x.ID == id); if (Data.Exists(AddOns.Path(directory: "Files", filename: solo.Name))) { Data.Move(AddOns.Path(directory: "Files", filename: solo.Name), AddOns.Path(directory: "Files", filename: audio.Name)); } solo.Name = audio.Name; solo.Size = audio.Size; await list.WriteToJson(); return(RedirectToAction(nameof(Index))); } catch (Exception ex) { await ex.LogAsync(); return(View()); } }
/// <inheritdoc /> public async Task MoveAndReplaceAsync(IStorageFile fileToReplace) { if (!this.Exists) { throw new StorageItemNotFoundException(this.Name, "Cannot move a file that does not exist."); } if (fileToReplace == null) { throw new ArgumentNullException(nameof(fileToReplace)); } if (!fileToReplace.Exists) { throw new StorageItemNotFoundException( fileToReplace.Name, "Cannot move to and replace a file that does not exist."); } await TaskSchedulerAwaiter.NewTaskSchedulerAwaiter(); var newPath = fileToReplace.Path; File.Delete(newPath); File.Move(this.Path, newPath); this.Path = newPath; this.Parent = fileToReplace.Parent; }
public void Save() { var xmlSerializer = new XmlSerializer(typeof(DatabaseInformation)); var info = new DatabaseInformation { disks = new List <DiskInformation> () }; InvokeEvent(this.OnStartDatabaseSave); foreach (var disk in from disk in this.disks select disk.Value) { InvokeEvent(this.OnStartDiskPreparing, disk.Index); info.disks.Add((disk as Disk).ToDiskInformation()); InvokeEvent(this.OnEndDiskPreparing, disk.Index); } InvokeEvent(this.OnStartDatabaseFileSave, this.location); var tempLocation = Path.GetTempFileName(); using (var fileStream = new FileStream(tempLocation, FileMode.Create, FileAccess.Write)) using (var gzipStream = new GZipStream(fileStream, CompressionMode.Compress)) xmlSerializer.Serialize(gzipStream, info); if (SystemFile.Exists(this.location)) { SystemFile.Delete(this.location); } SystemFile.Move(tempLocation, this.location); InvokeEvent(this.OnEndDatabaseFileSave, this.location); InvokeEvent(this.OnEndDatabaseSave); }
///////////////////////////////////// // GENERIC METHODS // ///////////////////////////////////// // pretty cool, credit to: https://stackoverflow.com/a/2553245/11000333 // sligthly modified to make a "copy directory" routine public static void MoveDirectory(string source, string target, bool copy = false) { var sourcePath = source.TrimEnd('\\', ' '); var targetPath = target.TrimEnd('\\', ' '); var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories) .GroupBy(s => Path.GetDirectoryName(s)); foreach (var folder in files) { var targetFolder = folder.Key.Replace(sourcePath, targetPath); if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } foreach (var file in folder) { var targetFile = Path.Combine(targetFolder, Path.GetFileName(file)); if (File.Exists(targetFile)) { File.Delete(targetFile); } if (!copy) { File.Move(file, targetFile); } else if (copy) { File.Copy(file, targetFile); } } } Directory.Delete(source, true); }
public override void Rename(string path, string name) { var extension = new FileInfo(path).Extension; var directoryPath = System.IO.Directory.GetParent(path).FullName; File.Move(path, directoryPath + "\\" + name + extension); }
public override async Task Download(Archive a, string destination) { var downloader = (ManualDownloader)GetDownloader(); var absPath = Path.Combine(downloader._downloadfolder.Path, a.Name); lock (downloader) { try { Utils.Log($"You must manually visit {Url} and download {a.Name} file by hand."); Utils.Log($"Waiting for {a.Name}"); downloader._watcher.EnableRaisingEvents = true; var watcher = downloader._fileEvents .Where(f => f.Size == a.Size) .Where(f => f.FullPath.FileHash(true) == a.Hash) .Buffer(new TimeSpan(0, 5, 0), 1) .Select(x => x.FirstOrDefault()) .FirstOrDefaultAsync(); Process.Start(Url); absPath = watcher.Wait()?.FullPath; if (!File.Exists(absPath)) { throw new InvalidDataException($"File not found after manual download operation"); } File.Move(absPath, destination); } finally { downloader._watcher.EnableRaisingEvents = false; } } }
/// <summary> /// Rename the file if necessary /// Called by Save and SaveAll /// </summary> /// <param name = "song"></param> /// <param name="newFileName"></param> private bool RenameFile(SongData song, out string newFileName) { newFileName = ""; var originalFileName = Path.GetFileName(song.FullFileName); if (originalFileName != song.FileName) { var ext = Path.GetExtension(song.FileName); var filename = Path.GetFileNameWithoutExtension(song.FileName); var path = Path.GetDirectoryName(song.FullFileName); newFileName = Path.Combine(path, $"{filename}{ext}"); // Check, if the New file name already exists // Don't change the newfilename, when only the Case change happened in filename int i = 1; if (File.Exists(newFileName) && originalFileName.ToLowerInvariant() != song.FileName.ToLowerInvariant()) { newFileName = Path.Combine(path, $"{filename} ({i}){ext}"); while (File.Exists(newFileName)) { i++; newFileName = Path.Combine(path, $"{filename} ({i}){ext}"); } } File.Move(song.FullFileName, newFileName); log.Debug($"Save: Renaming Song: {song.FullFileName} Newname: {newFileName}"); return(true); } return(false); }
public bool MoveFile(string path, string filename, string filenameExt, bool x86) { try { if (!x86) { filename = UppercaseString(filename); Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\" + filename); File.Move(path, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\" + filename + "\\" + filenameExt); WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu) + "\\Programs\\" + filename + ".lnk"); shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\" + filename + "\\" + filenameExt; shortcut.Save(); } else { filename = UppercaseString(filename); Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\" + filename); File.Move(path, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\" + filename + "\\" + filenameExt); WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu) + "\\Programs\\" + filename + ".lnk"); shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\" + filename + "\\" + filenameExt; shortcut.Save(); } return(true); } catch { return(false); } }
protected static void ScaleImage(string path, int maxWidth, int maxHeight, out string height, out string Aratio) { var image = System.Drawing.Image.FromFile(path); var ratio = (double)maxWidth / image.Width; Aratio = ratio.ToString(); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); height = newHeight.ToString(); var newImage = new Bitmap(newWidth, newHeight); var g = Graphics.FromImage(newImage); g.DrawImage(image, 0, 0, newWidth, newHeight); Bitmap bmp = new Bitmap(newImage); try { bmp.Save(path.Replace(".png", "a.png"), ImageFormat.Png); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); throw; } image.Dispose(); File.Delete(path); File.Move(path.Replace(".png", "a.png"), path); }
private Message SavePostedFile(string postedFilePath, SessionModel model) { var fileInfo = new FileInfo(postedFilePath); if (fileInfo.Length > Convert.ToInt64(_config["MaxUploadSizeBytes"])) { BadHttpRequestException.Throw(RequestRejectionReason.InvalidContentLength, HttpMethod.Post); } var message = GetMessageFromModel(model, true); var uploadDir = Helper.GetUploadFolder(model.SessionId, _env.WebRootPath); if (!Directory.Exists(uploadDir)) { Directory.CreateDirectory(uploadDir); } // Use original file name var fileName = message.Text; if (IOFile.Exists(Path.Combine(uploadDir, fileName))) { // if exist then append digits from the session id fileName = Path.GetFileNameWithoutExtension(message.Text) + "_" + message.Id.Substring(0, 6) + Path.GetExtension(message.Text); } var destUploadPath = Path.Combine(uploadDir, fileName); message.Text = fileName; message.HasFile = true; message.FileSizeBytes = fileInfo.Length; IOFile.Move(postedFilePath, destUploadPath); return(message); }
/// <summary> /// 文件拷贝 /// </summary> /// <param name="sfile">源文件路径</param> /// <param name="dfile">目的文件路径</param> /// <param name="sectSize">传输大小 1048576</param> /// <param name="type">文件扩展名</param> /// <param name="index">进度值</param> /// <returns>是否成功</returns> public static bool CopyFile(this string sfile, string dfile, int sectSize, string type, int index) { try { if (!Directory.Exists(Path.GetDirectoryName(dfile))) { Directory.CreateDirectory(Path.GetDirectoryName(dfile)); } FileStream fileToCreate = new FileStream(dfile, FileMode.Create); //创建目的文件,如果已存在将被覆盖 fileToCreate.Close(); //关闭所有资源 fileToCreate.Dispose(); //释放所有资源 FileStream formerOpen = new FileStream(sfile, FileMode.Open, FileAccess.Read); //以只读方式打开源文件 FileStream toFileOpen = new FileStream(dfile, FileMode.Append, FileAccess.Write); //以写方式打开目的文件 if (sectSize < formerOpen.Length) //如果分段拷贝,即每次拷贝内容小于文件总长度 { byte[] buffer = new byte[sectSize]; //根据传输的大小,定义一个字节数组 int copied = 0; //记录传输的大小 while (copied <= ((int)formerOpen.Length - sectSize)) //拷贝主体部分 { var fileSize = formerOpen.Read(buffer, 0, sectSize); //要拷贝的文件的大小 formerOpen.Flush(); //清空缓存 toFileOpen.Write(buffer, 0, sectSize); //向目的文件写入字节 toFileOpen.Flush(); //清空缓存 toFileOpen.Position = formerOpen.Position; //使源文件和目的文件流的位置相同 copied += fileSize; //记录已拷贝的大小 } int left = (int)formerOpen.Length - copied; //获取剩余大小 formerOpen.Read(buffer, 0, left); //读取剩余的字节 formerOpen.Flush(); //清空缓存 toFileOpen.Write(buffer, 0, left); //写入剩余的部分 toFileOpen.Flush(); //清空缓存 } else//如果整体拷贝,即每次拷贝内容大于文件总长度 { byte[] buffer = new byte[formerOpen.Length]; //获取文件的大小 formerOpen.Read(buffer, 0, (int)formerOpen.Length); //读取源文件的字节 formerOpen.Flush(); //清空缓存 toFileOpen.Write(buffer, 0, (int)formerOpen.Length); //写放字节 toFileOpen.Flush(); //清空缓存 } formerOpen.Dispose(); formerOpen.Close(); //释放所有资源 toFileOpen.Dispose(); toFileOpen.Close(); //释放所有资源 string a = Path.GetDirectoryName(dfile) + "\\" + Path.GetFileNameWithoutExtension(dfile) + type; if (File.Exists(a)) { File.Delete(a); } File.Move(dfile, a); File.Delete(sfile); return(true); } catch (Exception) { return(false); } }
public async Task <IActionResult> PostWithFileAfterStreaming(SessionModel model) { // Locate the file var uploadedPath = Path.Combine(Helper.GetUploadFolder(string.Empty, _env.WebRootPath), model.SocketConnectionId + ConversationHub.FILE_EXT); if (!IOFile.Exists(uploadedPath)) { return(NotFound()); } var message = GetMessageFromModel(model); var uploadFolder = Helper.GetUploadFolder(model.SessionId, _env.WebRootPath); var moveToPath = Path.Combine(uploadFolder, message.Id + ConversationHub.FILE_EXT); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } IOFile.Move(uploadedPath, moveToPath); var fileInfo = new FileInfo(moveToPath); if (!ModelState.IsValid || fileInfo.Length > Convert.ToInt64(_config["MaxUploadSizeBytes"])) { DeleteIfExists(moveToPath); return(BadRequest(ModelState)); } message.HasFile = true; message.FileSizeBytes = fileInfo.Length; return(await SaveMessageAndReturnResponse(message)); }
/// <summary> /// Перемещает весь каталог со всем его содержимым в новый каталог либо только файлы из текущего каталога. /// </summary> /// <param name="NewName">Путь, куда нужно переместить.</param> /// <param name="onlyFiles">При значении true — перемещает только файлы текущего каталога.</param> public void moveto(string NewName, bool onlyFiles) { if (!SDirectory.Exists(dname) & dname.Length <= 260 & NewName.Length <= 260)//проверка на существование директории, корректности имени перемещаемой папки и принимающей перемещение { try { if (!onlyFiles) { SDirectory.Move(dname, NewName); //создание директории dname = NewName; //переопределение рабочей папки } else { DirectoryInfo _d = new DirectoryInfo(dname); foreach (string f in SDirectory.GetFiles(dname)) { SFile.Move(f, NewName); } } } catch (Exception e) //обработка исключений для перемещения { LogForOperations("Перемещение папки", e.Message); //запись ошибки (если есть) в лог throw e; } } else { LogForOperations("Перемещение папки", "операция с папкой невозможна, т.к. перемещаемая папка не существует либо в имени больше 260 символов, либо папка с новым именем уже существует");//запись ошибки в лог, если не выполнилась проверка } }
/// <summary> /// Перемещение файла. /// </summary> /// <param name="NewName">Путь, куда нужно переместить.</param> /// <param name="onlyFiles">При значении true — перемещает только файлы из папки.</param> public void moveto(string NewName, bool onlyFiles) { stream.Close(); if (SFile.Exists(fname) & fname.Length <= 260 & NewName.Length <= 260)//проверка на существование файла и корректность имени, пути { if (onlyFiles) { try { if (!SDirectory.Exists(NewName)) //проверка папки, в которую надо переместить, на существование { SDirectory.CreateDirectory(NewName); //создание папки, в которую надо переместить } SFile.Move(fname, NewName); //перемещение файла fname = NewName; //переопределение рабочего пути } catch (Exception ex) //обработка исключений для перемещения { LogForOperations("Перемещение файла", ex.Message); //запись ошибки в лог (если есть) throw ex; } } else { LogForOperations("Перемещение файла", "операция отменена, т.к. значение параметра = '0'");//запись ошибки(если есть) в лог } } else { LogForOperations("Перемещение файла", "файл не существует либо содержит в своем имени более 260 символов, либо папка, в которую происходит перемещение, содержит в имени более 260 символов");//запись ошибки в лог, если не выполняется условие проверки } }
/// <summary> /// Переименовывание файла. /// </summary> /// <param name="NewName">Новое имя.</param> public void rename(string NewName) { stream.Close(); //закрываем поток if (SFile.Exists(fname) & fname.Length <= 260 & NewName.Length <= 260) //проверка на существование файла и корректность имени, нового имени { try { if (!SFile.Exists(NewName)) //проверка файла на отсутствие по новому пути { SFile.Move(fname, NewName); //перемещение файла } else { LogForOperations("Переименование файла", "файл с таким именем уже существует");//запись в лог ошибки } } catch (Exception ex) //обработка исключений для переименования { LogForOperations("Переименование файла", ex.Message); //запись в лог оибки (если есть) throw ex; } } else { LogForOperations("Переименование файла", "файл не существует либо содержит в своем имени более 260 символов, либо новое имя содержит более 260 символов");//запись ошибки в лог, если не выполняется условие проверки } }
private static void move(string appOnline, string appDownloaded, bool overwrite) { if (File.Exists(appDownloaded) && overwrite) { File.Delete(appDownloaded); } File.Move(appOnline, appDownloaded); }
private void SaveAsSVF(Document Doc) { using (new HeartBeat()) { LogTrace("** Saving SVF"); try { ApplicationAddIn svfAddin = _inventorApplication .ApplicationAddIns .Cast <ApplicationAddIn>() .FirstOrDefault(item => item.ClassIdString == "{C200B99B-B7DD-4114-A5E9-6557AB5ED8EC}"); var oAddin = (TranslatorAddIn)svfAddin; if (oAddin != null) { Trace.TraceInformation("SVF Translator addin is available"); TranslationContext oContext = _inventorApplication.TransientObjects.CreateTranslationContext(); // Setting context type oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism; NameValueMap oOptions = _inventorApplication.TransientObjects.CreateNameValueMap(); // Create data medium; DataMedium oData = _inventorApplication.TransientObjects.CreateDataMedium(); Trace.TraceInformation("SVF save"); var sessionDir = Path.Combine(Directory.GetCurrentDirectory(), "SvfOutput"); oData.FileName = Path.Combine(sessionDir, "result.collaboration"); var outputDir = Path.Combine(sessionDir, "output"); var bubbleFileOriginal = Path.Combine(outputDir, "bubble.json"); var bubbleFileNew = Path.Combine(sessionDir, "bubble.json"); // Setup SVF options if (oAddin.get_HasSaveCopyAsOptions(Doc, oContext, oOptions)) { oOptions.set_Value("GeometryType", 1); oOptions.set_Value("EnableExpressTranslation", false); oOptions.set_Value("SVFFileOutputDir", sessionDir); oOptions.set_Value("ExportFileProperties", true); oOptions.set_Value("ObfuscateLabels", false); } LogTrace($"SVF files are output to: {oOptions.get_Value("SVFFileOutputDir")}"); oAddin.SaveCopyAs(Doc, oContext, oOptions, oData); Trace.TraceInformation("SVF can be exported."); LogTrace($"** Saved SVF as {oData.FileName}"); File.Move(bubbleFileOriginal, bubbleFileNew); } } catch (Exception e) { LogError($"********Export to format SVF failed: {e.Message}"); } } }
public void SyncLocalFilePVs(CollectionDiff <PVForSong, PVForSong> diff, int songId) { var addedLocalMedia = diff.Added.Where(m => m.Service == PVService.LocalFile); foreach (var pv in addedLocalMedia) { var oldFull = Path.Combine(Path.GetTempPath(), pv.PVId); if (Path.GetDirectoryName(oldFull) != Path.GetDirectoryName(Path.GetTempPath())) { throw new InvalidOperationException("File folder doesn't match with temporary folder"); } if (!Extensions.Contains(Path.GetExtension(oldFull))) { throw new InvalidOperationException("Invalid extension"); } var newId = $"{pv.Author}-S{songId}-{pv.PVId}"; var newFull = GetFilesystemPath(newId); pv.PVId = newId; try { File.Move(oldFull, newFull); // Remove copied permissions, reset to inherited http://stackoverflow.com/a/2930969 var newFullFileInfo = new FileInfo(newFull); var fs = newFullFileInfo.GetAccessControl(); fs.SetAccessRuleProtection(false, false); newFullFileInfo.SetAccessControl(fs); CreateThumbnail(newFull, newId, pv); } catch (IOException x) { s_log.Error(x, "Unable to move local media file: " + oldFull); throw; } } foreach (var pv in diff.Removed.Where(m => m.Service == PVService.LocalFile)) { var fullPath = GetFilesystemPath(pv.PVId); if (File.Exists(fullPath)) { try { File.Delete(fullPath); } catch (IOException x) { s_log.Error(x, "Unable to delete local media file: " + fullPath); } } } }
public async Task <IActionResult> DeleteUploadedFile([FromRoute] string id, [FromRoute] string filename) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else if (!artifactExists(id)) { return(NotFound(id)); } var artifact = _context.Artifacts.Include(asi => asi.StorageItems).Single(ar => ar.ID == id); if (artifact.StorageItems?.Count == 0) { return(NotFound(filename)); } var file = artifact.StorageItems?.SingleOrDefault(asi => asi.Filename == filename); if (file == null) { return(NotFound(filename)); } else { var filePath = Path.Combine(_storagePath, artifact.ID, file.Filename); if (!IOF.Exists(filePath)) { return(NotFound("File does not exist on server!")); } else { // Move the File (Versioning) var newFileName = $"{filename}.v{artifact.Version}"; var newFilePath = $"{filePath}.v{artifact.Version}"; IOF.Move(filePath, newFilePath); // Remove Entries in StorageItems DB artifact.StorageItems?.Remove(file); // Generate backup entry file.Filename = newFileName; _context.ArtifactsBackup.Add(generateBackup(artifact, file)); // Increase the latest version of the artifact artifact.Version++; _context.Artifacts.Update(artifact); await _context.SaveChangesAsync(); return(Ok()); } } }
public static bool TryGenerateExplorerIcon(File file) { string path = file.GetAbsolutePath(); if (!F.Exists(path)) { return(false); } try { string ext = P.GetExtension(path).Replace(".", string.Empty); if (file.IsFolder) { //string guid = GetGuidFromString("folder").ToString(); ////文件夹,统一图标 //if (!F.Exists(GetExplorerIconPath(guid))) //{ // var iconPath = GetExplorerIconPath(guid); // ExplorerIcon.GetBitmapFromFolderPath(path, ExplorerIcon.IconSizeEnum.ExtraLargeIcon).Save(iconPath, ImageFormat.Png); //} //file.IconGUID = guid; } else if (FileUtility.IsExecutable(path)) { //程序文件,每个图标都不同 string guid = Guid.NewGuid().ToString(); var iconPath = GetExplorerIconPath(file); ExplorerIcon.GetBitmapFromFilePath(path, ExplorerIcon.IconSizeEnum.ExtraLargeIcon) .Save(iconPath, ImageFormat.Png); } else { var iconPath = GetExplorerIconPath(file); //其他文件,同一个格式的用同一个图标 if (F.Exists(iconPath)) { } else { string tempPath = P.GetTempFileName(); ExplorerIcon.GetBitmapFromFilePath(path, ExplorerIcon.IconSizeEnum.ExtraLargeIcon).Save(tempPath, ImageFormat.Png); try { F.Move(tempPath, iconPath); } catch { } }; } } catch (Exception ex) { } return(false); }
public void HandleBookRename_CaseChangeOnly_WorksRight() { // Setup // const string originalBookName = "A new book"; var bookBuilder = new BookFolderBuilder() .WithRootFolder(_collectionFolder.FolderPath) .WithTitle(originalBookName) .WithHtm("<html><body>This is just a dummy</body></html>") .Build(); string bookFolderPath = bookBuilder.BuiltBookFolderPath; string htmlPath = bookBuilder.BuiltBookHtmPath; TeamCollectionManager.ForceCurrentUserForTests("*****@*****.**"); _collection.PutBook(bookFolderPath); var locked = _collection.AttemptLock(originalBookName); Assert.That(locked, Is.True, "successfully checked out book to [email protected]"); // SUT: rename changes status in local collection folder, but not in shared repo folder const string newBookName = "A New Book"; var newBookFolderPath = Path.Combine(_collectionFolder.FolderPath, newBookName); File.Move(htmlPath, Path.Combine(bookFolderPath, newBookName + ".htm")); // renaming directory doesn't work when names are 'the same' var tempPath = Path.Combine(_collectionFolder.FolderPath, "tempxxyy"); Directory.Move(bookFolderPath, tempPath); Directory.Move(tempPath, newBookFolderPath); _collection.HandleBookRename(originalBookName, newBookName); _collection.PutBook(newBookFolderPath, true); var newRepoPath = Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom"); // It should not have been deleted! This is a regression test for BL-10156. // The danger is that Windows considers the old and new names the same, so after // we move the file to the new name, if we go to delete the old name, we get rid of the new one. Assert.That(File.Exists(newRepoPath)); // Did it get renamed? var matchingFiles = Directory.EnumerateFiles(Path.Combine(_sharedFolder.FolderPath, "Books"), newBookName + ".bloom").ToArray(); Assert.That(matchingFiles[0], Is.EqualTo(Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom"))); var newStatus = _collection.GetLocalStatus(newBookName); var repoStatus = _collection.GetStatus(newBookName); Assert.That(newStatus, Is.Not.Null, "local status of renamed book is not null"); Assert.That(repoStatus, Is.Not.Null, "repo status of renamed book is not null"); Assert.That(newStatus.checksum, Is.EqualTo(repoStatus.checksum), "checksums of local and remote match after rename"); Assert.That(newStatus.lockedBy, Is.EqualTo(null), "lockedBy of local and remote match after rename"); Assert.That(newStatus.oldName, Is.Null, "local status has original name cleared after commit"); }
/// <summary> /// Renames the file to the new structure /// </summary> /// <param name="baseInfoTag">Metadatas of the file</param> /// <returns>The new full path of the file</returns> public static string RenameFile(BaseInfoTag baseInfoTag) { try { if (!string.IsNullOrWhiteSpace(baseInfoTag.JoinedPerformers) && !string.IsNullOrWhiteSpace(baseInfoTag.Title)) { var oldFileInfo = new FileInfo(baseInfoTag.FileInfo); var path = oldFileInfo.DirectoryName; if (path != null) { var newFileName = $"{baseInfoTag.JoinedPerformers} - {baseInfoTag.Title}"; newFileName = newFileName.RemoveInvalidPathCharsAndToTitleCase().Trim(); var newFileInfo = new FileInfo(Path.Combine(path, $"{newFileName}{oldFileInfo.Extension.ToLower()}")); if (!newFileInfo.FullName.ToLower().Equals(oldFileInfo.FullName.ToLower())) { var counter = 1; var isTheSame = false; while (newFileInfo.Exists) { isTheSame = newFileInfo.FullName.ToLower().Equals(oldFileInfo.FullName.ToLower()); if (isTheSame) { break; } var tempFileName = $"{newFileName} ({counter++})"; newFileInfo = new FileInfo(Path.Combine(path, $"{tempFileName}{oldFileInfo.Extension.ToLower()}")); } if (!isTheSame) { // Datei umbenennen Logger.Info( $"Renaming \"{oldFileInfo.FullName}\"\r\n to \"{newFileInfo.FullName}\""); File.Move(baseInfoTag.FileInfo, newFileInfo.FullName); return(newFileInfo.FullName); } } } } return(Actiontype.Already.ToString()); } catch (Exception ex) { Logger.Error($"{ex.Message} -> \"{baseInfoTag.FileInfo}\"", ex); return(Actiontype.Exception.ToString()); } }
public void UpdateLocalFiles() { try { StringBuilder logResult = new StringBuilder(); _allBasicBooksWithoutRealUrl = BookManager.GetBasicBooksWithoutDownloadUrl(StartNum, EndNum); var mapping = GetFileMapping(); if (!string.IsNullOrEmpty(Folder) && Directory.Exists(Folder)) { DirectoryInfo directory = new DirectoryInfo(Folder); FileInfo[] fileInfos = directory.GetFiles(); foreach (var fileInfo in fileInfos) { if (string.Equals(fileInfo.Extension, ".html", StringComparison.OrdinalIgnoreCase) && fileInfo.Length < 1024 * 1024) { fileInfo.Delete(); continue; } string fileNameWithoutExtension = fileInfo.Name; if (!string.IsNullOrEmpty(fileInfo.Extension)) { fileNameWithoutExtension = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.')); } string key = fileNameWithoutExtension.ToUpper(); if (mapping.ContainsKey(key)) { logResult.AppendLine(string.Format("Rename: {0} -> {1}", fileInfo.Name, mapping[key])); IOFile.Move(fileInfo.FullName, GetFileName(Path.Combine(Folder, mapping[key]))); } else if (!string.Equals(fileInfo.Extension, ".pdf", StringComparison.OrdinalIgnoreCase)) { logResult.AppendLine(string.Format("Adjust Extension: {0}", fileInfo.Name)); string destinationFilePath = GetFileName(Path.Combine(Folder, string.Format("{0}.pdf", fileNameWithoutExtension))); IOFile.Move(fileInfo.FullName, destinationFilePath); } } _logger.Log(logResult.ToString()); //BookManager.UpdateBasicBooksInfo(_allBasicBooksWithoutRealUrl); AddMessage("Updated Successed!", MessageType.Success); } else { AddMessage("Invalid Folder!", MessageType.Error); } } catch (Exception ex) { _logger.Log(LogLevel.Error, "Update local files failed"); _logger.Log(ex); } }
/// <summary> /// Confirms the file tags can actually be read, proving the file is valid. /// TODO: Possibly find a better way to validate more file types quicker /// TODO: perhaps by reading the resolved url ending rather than assuming mp3 immediately /// </summary> /// <returns>True if the file was downloaded correctly and can be modified</returns> public override async Task <bool> Validate() { var valid = false; var retry = false; SFile file = null; try { // Test if the file is a valid mp3 file = SFile.Create(MainResource.AbsolutePath); } catch (CorruptFileException) // File isn't mp3 { try { // Check if the file is wma var old = MainResource.AbsolutePath; MainResource.AbsolutePath = MainResource.AbsolutePath.Substring(0, MainResource.AbsolutePath.Length - 3) + "wma"; File.Move(old, MainResource.AbsolutePath); file = SFile.Create(MainResource.AbsolutePath); } catch (CorruptFileException e) // File isn't any supported type { File.Delete(MainResource.AbsolutePath); // If manual has already been attempted, this isn't possible retry = !_forceManual; if (!retry) { View.Report("Error!", true); CrashHandler.Throw("Unable to download a valid song format for editing!", e); } } } finally { if (file != null) { valid = true; file.Dispose(); } } // Retry the download if necessary if (retry) { valid = await RetryDownload(); } return(valid); }
static void RenameFiles() { var path = @"C:\Users\Arash\Downloads\Compressed\ESL Podcast - Lessons 051-200 [www.langdownload.com]"; DirectoryInfo mainDir = new DirectoryInfo(path); var files = mainDir.GetFiles(); foreach (FileInfo f in files) { File.Move(f.FullName, f.DirectoryName + "\\new\\" + f.Name.Replace("[www.langdownload.com]", "")); } }
public async Task <IActionResult> PostWithFile() { FormValueProvider formModel; var postedFilePath = Path.GetTempFileName(); using (var stream = IOFile.Create(postedFilePath)) { formModel = await Request.StreamFile(stream); } var model = new SessionModel(); var bindingSuccessful = await TryUpdateModelAsync(model, prefix : "", valueProvider : formModel); if (!bindingSuccessful) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } var fileInfo = new FileInfo(postedFilePath); if (fileInfo.Length > Convert.ToInt64(_config["MaxUploadSizeBytes"])) { return(BadRequest()); } var message = GetMessageFromModel(model, true); var uploadDir = GetUploadFolder(model.SessionId, _env.WebRootPath); if (!Directory.Exists(uploadDir)) { Directory.CreateDirectory(uploadDir); } // Use original file name var fileName = message.Text; if (IOFile.Exists(Path.Combine(uploadDir, fileName))) { // if exist then append digits from the session id fileName = Path.GetFileNameWithoutExtension(message.Text) + "_" + message.Id.Substring(0, 6) + Path.GetExtension(message.Text); } var destUploadPath = Path.Combine(uploadDir, fileName); message.Text = fileName; message.HasFile = true; message.FileSizeBytes = fileInfo.Length; IOFile.Move(postedFilePath, destUploadPath); return(await SaveMessageAndReturnResponse(message)); }
public bool Rename(string sourceKey, string targetKey) { var sourcePath = ComputePath(sourceKey); var targetPath = ComputePath(targetKey); var targetDirectory = Path.GetDirectoryName(targetPath); EnsureDirectoryExists(targetDirectory, create: true); IOFile.Move(sourcePath, targetPath); return(true); }
public Organizer(string root) { _root = root; var moviesFolder = Directory.GetFiles(root); var regex = new Regex(@"^(?<name>(\w+ [ ]*)+)\[\d+].\w+", RegexOptions.Compiled); var api = new ImdbApi.ImdbApi(); CreateDirectoryIfDoesntExist("All"); CreateDirectoryIfDoesntExist("Unsorted"); foreach (var path in moviesFolder) { try { var filename = Path.GetFileName(path); var extension = Path.GetExtension(path); if (extension == ".dll" || extension == ".exe") { continue; } var match = regex.Match(filename); var movieName = match.Groups["name"].Value; Console.WriteLine("File: " + filename); if (!string.IsNullOrEmpty(movieName)) { Console.WriteLine("Found movie: " + movieName); var info = api.GetMovieInfo(movieName); if (string.IsNullOrEmpty(info.Error)) { var newPath = MoveFilePath("All", filename); File.Move(path, newPath); foreach (var genre in info.GenresArray) { CreateDirectoryIfDoesntExist(genre); MakeShortcut(newPath, MoveFilePath(genre, filename)); } continue; } } File.Move(path, MoveFilePath("Unsorted", filename)); Console.WriteLine("Moved to /Unsorted"); Console.WriteLine(""); } catch (Exception e) { Console.WriteLine("The process failed for file: {0}\n", path); } } }
private void ConvertProject() { openFileDialog1.FileName = ""; openFileDialog1.Filter = "Inventor Part Document|*.ipt"; openFileDialog1.Title = NAME_PROJECT; openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { File.Move(openFileDialog1.FileName, openFileDialog1.FileName.Replace(".ipt", ".step"));// переименование файла MessageBox.Show("Файл " + openFileDialog1.FileName + " изменен на \n" + openFileDialog1.FileName.Replace(".ipt", ".step")); } }
internal static void Load() { if (Trajectories.Settings == null) { return; } Util.Log("Loading settings"); config ??= PluginConfiguration.CreateForType <Settings>(); try { config.load(); } catch (XmlException e) { if (ConfigError) { throw; // if previous error handling failed, we give up } ConfigError = true; Util.LogError("Loading config: {0}", e.ToString()); string TrajPluginPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Util.Log("Installed at: {0}", TrajPluginPath); TrajPluginPath += "/PluginData/" + Assembly.GetExecutingAssembly().FullName + "/config.xml"; if (File.Exists(TrajPluginPath)) { Util.Log("Clearing config file..."); int idx = 1; while (File.Exists(TrajPluginPath + ".bak." + idx)) { ++idx; } File.Move(TrajPluginPath, TrajPluginPath + ".bak." + idx); Util.Log("Creating new config..."); config.load(); Util.Log("New config created"); } else { Util.Log("No config file exists"); throw; } } Serialize(); }