private async Task <JobResource> UploadResourceAndGetInfoAsync(string filePath, ResourceType resourceType, string driverUploadPath, string localizedName = null) { if (!_file.Exists(filePath)) { Exceptions.Throw( new FileNotFoundException("Could not find resource file " + filePath), Log); } var detailsOutputPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); try { await _javaLauncher.LaunchAsync( JavaLoggingSetting.Info, JavaClassNameForResourceUploader, filePath, resourceType.ToString(), driverUploadPath, detailsOutputPath); var localizedResourceName = localizedName ?? Path.GetFileName(filePath); return(ParseGeneratedOutputFile(detailsOutputPath, localizedResourceName, resourceType)); } finally { if (_file.Exists(detailsOutputPath)) { _file.Delete(detailsOutputPath); } } }
private void MoveLogFileIfOld() { var newFilePath = _detailedLogFile.GetNewFileName(); _fileWrapper.Copy(_detailedLogFile.LogFilePath, Path.Combine(_detailedLogFile.LogFilePath, newFilePath)); _fileWrapper.Delete(_detailedLogFile.LogFilePath); }
/// <summary> /// Downloads the resource at the URI specified by in the address parameter. /// When the download completes successfully, the downloaded file is named fileName on the local computer. /// </summary> /// <param name="address"></param> /// <param name="tmpFileName"></param> /// <param name="dontStartUpdate"></param> /// <param name="fileName"></param> /// <param name="checkSum"></param> public void Download(Uri address, string tmpFileName, bool dontStartUpdate, string fileName, string checkSum) { _tmpFileName = tmpFileName; if (_file.Exists(_tmpFileName)) { _file.Delete(_tmpFileName); } _dontStartUpdate = dontStartUpdate; _webClient.DownloadFileAsync(address, tmpFileName, tmpFileName); _webClient.DownloadFileCompleted += (o, args) => { if (!args.Cancelled && null == args.Error && PerformCheckSum(tmpFileName, checkSum)) { _file.Move(tmpFileName, fileName); OnDownloadFileCompleted(args, fileName); } else { _file.Delete(tmpFileName); ProgressDialog.Close(); } }; ProgressDialog.Show(); IsBusyDownloading = true; }
public string UnZip(IActivityIOOperationsEndPoint src, IActivityIOOperationsEndPoint dst, IDev2UnZipOperationTO args) { string status; try { status = ValidateUnzipSourceDestinationFileOperation(src, dst, args, () => { ZipFile zip; var tempFile = string.Empty; if (src.RequiresLocalTmpStorage()) { var tmpZip = CreateTmpFile(); using (var s = src.Get(src.IOPath, _filesToDelete)) { _fileWrapper.WriteAllBytes(tmpZip, s.ToByteArray()); } tempFile = tmpZip; zip = ZipFile.Read(tempFile); } else { zip = ZipFile.Read(src.Get(src.IOPath, _filesToDelete)); } if (dst.RequiresLocalTmpStorage()) { // unzip locally then Put the contents of the archive to the dst end-point var tempPath = _common.CreateTmpDirectory(); _common.ExtractFile(args, zip, tempPath); var endPointPath = ActivityIOFactory.CreatePathFromString(tempPath, string.Empty, string.Empty); var endPoint = ActivityIOFactory.CreateOperationEndPointFromIOPath(endPointPath); Move(endPoint, dst, new Dev2CRUDOperationTO(args.Overwrite)); } else { _common.ExtractFile(args, zip, dst.IOPath.Path); } if (src.RequiresLocalTmpStorage()) { _fileWrapper.Delete(tempFile); } return(ResultOk); }); } finally { _filesToDelete.ForEach(RemoveTmpFile); } return(status); }
private async Task PublishWithCustomWebConfig(IRunProcess runner, IFile webConfig) { await WriteWebConfig(webConfig); await ExecutePublishProcess(runner); webConfig.Delete(); }
private void WriteUsers(IEnumerable <UserIdentity> users) { var path = GetFilePath(); var name = _path.GetFileNameWithoutExtension(path); var dir = _path.GetDirectoryName(path); if (dir == null) { throw new Exception("Cannot get repository directory"); } var backup = _path.Combine(dir, name + ".bak"); // Remove Backup if (_file.Exists(backup)) { _file.Delete(backup); } // Rename existing file if (_file.Exists(path)) { _file.Move(path, backup); } var orderedUsers = users.OrderBy(user => user.Id).ToList(); _file.WriteAllText(path, JsonConvert.SerializeObject(orderedUsers, Formatting.Indented)); }
public void Clear() { if (file.Exists) { file.Delete(); } }
private static VerifiedFile RevertFileState(IFile file) { if (!file.Exists) { File.WriteAllText($"{file.FullName}.delete", "..."); return(null); } else if (File.Exists($"{file.FullName}.delete")) { file.Delete(); return(null); } else { var backupFile = new FileInfo($"{file.FullName}.backup"); if (!backupFile.Exists) { Assert.Fail($"Expected backup file {file.FullName}.backup does not exist"); } backupFile.CopyTo(file.FullName, overwrite: true); } return(file as VerifiedFile); }
public static void CleanAssetBundleFolder(IFile file, string pathToSearch, string[] assetBundlesList, Dictionary <string, string> lowerToUpperDictionary) { for (int i = 0; i < assetBundlesList.Length; i++) { if (string.IsNullOrEmpty(assetBundlesList[i])) { continue; } try { //NOTE(Brian): This is done for correctness sake, rename files to preserve the hash upper-case if (lowerToUpperDictionary.TryGetValue(assetBundlesList[i], out string hashWithUppercase)) { string oldPath = pathToSearch + assetBundlesList[i]; string path = pathToSearch + hashWithUppercase; file.Move(oldPath, path); } string oldPathMf = pathToSearch + assetBundlesList[i] + ".manifest"; file.Delete(oldPathMf); } catch (Exception e) { Debug.LogWarning("Error! " + e.Message); } } }
public void Save(string path, UpdateFile updateFile) { IFile file = Disk.File(path + Path.AltDirectorySeparatorChar + UpdateFileStore.FILE_NAME); file.Delete(); file.Create(updateFile.Data.ToByte()); }
public static void DeleteWithTimeout(this IFile file) { int retryCount = 0; while (retryCount++ < RetryCount) { try { if (file.Exists) { file.Delete(); } return; } catch (IOException ex) { if (retryCount == RetryCount) { throw ex; } else { Thread.Sleep(RetryWaitInterval); } } } }
public void PostProcess(string outputFile, bool successful) { if (_fileSystem.Exists(outputFile) && Path.GetFileName(outputFile).IsTestFile(_configurationManager)) { _fileSystem.Delete(outputFile); } }
public static void DeleteIfExists(this IFile file) { if (file.Exists) { file.Delete(); } }
private static async Task MoveUsingFileSystem(IFile destination, IFile source, FileAttributes attributes) { if (SameVolume(destination.Path, source.Path)) { await Task.Run(() => { // this is a guard clause for a bad bug I can't duplicate. See issue # 79 MyDebug.Assert(source.Exists()); if (source.Exists()) { File.Delete(destination.Path); File.Move(source.Path, destination.Path); if (attributes != FileAttributes.Normal) { File.SetAttributes(destination.Path, attributes); } } }); return; } // else await FileSystemCopy(destination, source, attributes); source.Delete(); }
public bool TryCreateTextFile(string Path, string Content, FileCreationPermission CreationPermission, out IFile Result) { IFile file = this.GetFile(Path); if (file.Exists && CreationPermission == FileCreationPermission.AllowOverwrite) { file.Delete(); } if (!this.TryCreateFile(Path, out Result)) { return(false); } try { using (TextWriter writer = Result.GetTextWriter()) { writer.Write(Content); writer.Flush(); } } catch (Exception) { return(false); } return(true); }
public void RunCleanup() { List <CompletedQueuedDownloadBM> ToRemove = new List <CompletedQueuedDownloadBM>(); foreach (CompletedQueuedDownloadBM download in this.completedDownloads.Where(IsDeletable)) { if (download.DownloadHandler.Status == DownloadState.Completed) { string filename = download.DownloadHandler.Filename; IFile file = this.fileManager.GetFile(filename); if (file.Exists && file.Delete()) { this.logger.LogInformation($"File deleted for download with GUID: {download.DownloadID}"); ToRemove.Add(download); } else { this.logger.LogWarning($"File cannot be deleted or not exists for download with GUID: {download.DownloadID}"); } } } foreach (var item in ToRemove) { this.completedDownloads.Remove(item); } }
public IFile MoveFrom(IFile source, string targetName, bool overwrite) { this.CheckDeleted(); #pragma warning disable CS0618 // Type or member is obsolete string dest = Path.GetFileName(targetName); if (!Directory.IsValidFileName(dest)) { throw new DirectoryNotFoundException($"Filename {dest} is invalid."); } if (!source.Created) { throw new FileNotFoundException($"{source.UnsafeGetPath().FullName} could not be found."); } if (this.ContainsFile(dest) && !overwrite) { throw new IOException($"{source.Name} already exists in the target directory"); } // Preserve GUID if (!this.FileGuidProvider.TryGetGuid(source.UnsafeGetPath(), out Guid existingGuid)) { existingGuid = Guid.NewGuid(); } var file = this.OpenFile(dest, existingGuid); // unsafe usage here as optimization. source.UnsafeGetPath() .MoveTo(file.UnsafeGetPath().ToString(), overwrite); #pragma warning restore CS0618 // Type or member is obsolete source.Delete(); return(this.OpenFile(dest)); }
public void SendTestMail(ConversionProfile profile, Accounts accounts) { var currentProfile = profile.Copy(); currentProfile.AutoSave.Enabled = false; var job = CreateJob(currentProfile, accounts); _smtpMailAction.ApplyPreSpecifiedTokens(job); var result = _smtpMailAction.Check(job.Profile, job.Accounts, CheckLevel.Job); if (!result) { DisplayResult(result, job); return; } if (!TrySetJobPasswords(job, profile)) { return; } var testFile = _path.Combine(_path.GetTempPath(), _translation.AttachmentFile + ".pdf"); _file.WriteAllText(testFile, @"PDFCreator", Encoding.GetEncoding("Unicode")); job.OutputFiles.Add(testFile); result = _smtpMailAction.ProcessJob(job); DisplayResult(result, job); _file.Delete(testFile); }
private static void TryExpandingLinkFile(IFile link) { var value = link.ReadAllText(); if (!value.StartsWith("[link] ")) { return; } var relativePath = value.Substring("[link] ".Length) .Replace("%20", " "); var fs = link.FileSystem; var path = fs.Internals.Path; var fullPath = path.GetFullPath( path.Combine(link.Directory.FullName, relativePath)); var target = fs.ParseFile(fullPath); if (!target.Exists) { return; } link.Delete(); link.Directory.Create(); target.CopyTo(link.Directory, link.NameWithoutExtension); }
public T Load() { _storageHelper = new StoragePowerToysVersionInfo(FilePath, _jsonStorage); // Depending on the version number of the previously installed PT Run, delete the cache if it is found to be incompatible if (_storageHelper.ClearCache) { if (File.Exists(FilePath)) { File.Delete(FilePath); Log.Info($"Deleting cached data at <{FilePath}>", GetType()); } } if (File.Exists(FilePath)) { var serialized = File.ReadAllText(FilePath); if (!string.IsNullOrWhiteSpace(serialized)) { Deserialize(serialized); } else { LoadDefault(); } } else { LoadDefault(); } return(_data.NonNull()); }
private void DeleteFilesCallback(MessageInteraction interaction) { if (interaction.Response != MessageResponse.Yes) { IsDone?.Invoke(this, new MacroCommandIsDoneEventArgs(ResponseStatus.Cancel)); return; } var notDeletedFiles = new List <HistoricFile>(); foreach (var historicFile in _historicFiles) { try { if (_file.Exists(historicFile.Path)) { _file.Delete(historicFile.Path); } } catch { notDeletedFiles.Add(historicFile); } } if (notDeletedFiles.Count > 0) { NotfiyUserAboutNotDeletedFiles(notDeletedFiles); } IsDone?.Invoke(this, new MacroCommandIsDoneEventArgs(ResponseStatus.Success)); }
public void DeleteTest() { IFile textFile = FactoryProvider.getFactory(PersitenseTypes.FILE).Create(FileTypes.txt); Student newStudent = textFile.Create(student); Assert.IsTrue(textFile.Delete(newStudent)); }
public void Execute() { if (_fileToDelete.Exists()) { CheckFilePermissions(); _fileToDelete.Delete(); } }
void SaveTestToDisk(Guid resourceId, IServiceTestModelTO serviceTestModelTo) { var dirPath = GetTestPathForResourceId(resourceId); _directoryWrapper.CreateIfNotExists(dirPath); if (!string.Equals(serviceTestModelTo.OldTestName, serviceTestModelTo.TestName, StringComparison.InvariantCultureIgnoreCase)) { var oldFilePath = Path.Combine(dirPath, $"{serviceTestModelTo.OldTestName}.test"); _fileWrapper.Delete(oldFilePath); } var filePath = Path.Combine(dirPath, $"{serviceTestModelTo.TestName}.test"); serviceTestModelTo.Password = DpapiWrapper.EncryptIfDecrypted(serviceTestModelTo.Password); var sw = new StreamWriter(filePath, false); _serializer.Serialize(sw, serviceTestModelTo); }
public IActionResult Delete(string id) { if (fileWork.Read(id) == null) { return(NotFound()); } fileWork.Delete(id); return(NoContent()); }
public void Delete(string sessionKey) { var path = Path.Combine(_path, sessionKey); if (_file.Exists(path)) { _file.Delete(path); } }
public IList <IExplorerItem> DeleteVersion(Guid resourceId, string versionNumber) { var resource = _catalogue.GetResource(Guid.Empty, resourceId); var path = GetVersionFolderFromResource(resource); var files = _directory.GetFiles(path).FirstOrDefault(a => a.Contains(string.Format("{0}_{1}_", resource.VersionInfo.VersionId.ToString(), versionNumber))); _file.Delete(files); return(GetVersions(resourceId)); }
private Boolean TargetWriteable() { Boolean targetWriteable = true; if (_Target.Exists() && _Overwrite) { targetWriteable = !TargetFileReadOnly(); if (targetWriteable) { _Target.Delete(); } } else if (_Target.Exists() && !_Overwrite) { targetWriteable = false; } return(targetWriteable); }
protected override void Dispose(bool disposing) { CheckDisposed(); _disposed = true; _stream?.Dispose(); if (_file.Exists) { _file.Delete(); } }
public void DeleteCoverageReport(Guid resourceID, string reportName) { var dirPath = GetTestCoveragePathForResourceId(resourceID); var testFilePath = Path.Combine(dirPath, $"{reportName}.coverage"); if (_fileWrapper.Exists(testFilePath)) { _fileWrapper.Delete(testFilePath); if (TestCoverageReports.TryGetValue(resourceID, out List <IServiceTestCoverageModelTo> coverageReports)) { var foundReportToDelete = coverageReports.FirstOrDefault(to => to.ReportName.Equals(reportName, StringComparison.InvariantCultureIgnoreCase)); if (foundReportToDelete != null) { Dev2Logger.Debug("Removing Report: " + reportName + Environment.NewLine + Environment.StackTrace, GlobalConstants.WarewolfDebug); coverageReports.Remove(foundReportToDelete); } } } }
private void OnView(IFile signature) { this.dialogService.ActionSheet(new ActionSheetConfig() .Add("View", () => { if (!this.fileViewer.Open(signature)) this.dialogService.Alert("Cannot open file"); }) .Add("Delete", async () => { var r = await this.dialogService.ConfirmAsync("Are you sure you want to delete " + signature.Name); if (r) { signature.Delete(); this.List.Remove(signature); } }) .Add("Cancel") ); }
public static void PerformCleanup(IDirectory dir, string path, IFile file) { try { foreach(var v in dir.GetFiles(path).Where(a => a.Contains("tmp"))) file.Delete(v); } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { //best effort. } }