public static void ProcessImage(GalleryImage galleryImage, IFileSystem fileSystem, string virtualRoot, string originalFileName, Color backgroundColor) { string originalPath = virtualRoot + "FullSizeImages/" + galleryImage.ImageFile; string webSizeImagePath = virtualRoot + "WebImages/" + galleryImage.WebImageFile; string thumbnailPath = virtualRoot + "Thumbnails/" + galleryImage.ThumbnailFile; using (Stream stream = fileSystem.GetAsStream(originalPath)) { using (Bitmap originalImage = new Bitmap(stream)) { SetExifData(galleryImage, originalImage, originalFileName); } } fileSystem.CopyFile(originalPath, webSizeImagePath, true); mojoPortal.Web.ImageHelper.ResizeImage( webSizeImagePath, IOHelper.GetMimeType(Path.GetExtension(webSizeImagePath)), galleryImage.WebImageWidth, galleryImage.WebImageHeight, backgroundColor); fileSystem.CopyFile(originalPath, thumbnailPath, true); mojoPortal.Web.ImageHelper.ResizeImage( thumbnailPath, IOHelper.GetMimeType(Path.GetExtension(thumbnailPath)), galleryImage.ThumbNailWidth, galleryImage.ThumbNailHeight, backgroundColor); }
internal bool BackupProject(string backupLocation, string xprojLocation, string projectName, IVsUpgradeLogger pLogger) { var directory = Path.GetDirectoryName(xprojLocation); // Back up the xproj and project.json to the backup location. var xprojName = Path.GetFileName(xprojLocation); var backupXprojPath = Path.Combine(backupLocation, xprojName); var projectJsonPath = Path.Combine(directory, "project.json"); var backupProjectJsonPath = Path.Combine(backupLocation, "project.json"); // We don't need to check the xproj path. That's being given to us by VS and was specified in the solution. if (!_fileSystem.FileExists(projectJsonPath)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectJsonPath, string.Format(VSResources.XprojMigrationFailedProjectJsonFileNotFound, projectName, projectJsonPath)); return(false); } pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, xprojLocation, string.Format(VSResources.MigrationBackupFile, xprojLocation, backupXprojPath)); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, projectJsonPath, string.Format(VSResources.MigrationBackupFile, projectJsonPath, backupProjectJsonPath)); _fileSystem.CopyFile(xprojLocation, backupXprojPath, true); _fileSystem.CopyFile(projectJsonPath, backupProjectJsonPath, true); return(true); }
private void ExtractFFMpeg(FFMpegInstallInfo downloadinfo, string tempFile, string targetFolder) { _logger.Info("Extracting ffmpeg from {0}", tempFile); var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString()); _fileSystem.CreateDirectory(tempFolder); try { ExtractArchive(downloadinfo, tempFile, tempFolder); var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories) .ToList(); foreach (var file in files.Where(i => { var filename = Path.GetFileName(i); return (string.Equals(filename, downloadinfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) || string.Equals(filename, downloadinfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase)); })) { var targetFile = Path.Combine(targetFolder, Path.GetFileName(file)); _fileSystem.CopyFile(file, targetFile, true); SetFilePermissions(targetFile); } } finally { DeleteFile(tempFile); } }
private void CacheFile(List <RunProcessJob> runProcessJobs, IFileSystem filesDir, string filePath, Cache cache) { // Either we copy the archive or we copy the extracted contents // copying the archive is faster so we'll do that instead and later delete it. var extension = Path.GetExtension(filePath).ToLowerInvariant(); var dirPath = PathHelper.GetFilePathWithoutExtension(filePath); switch (extension) { case ".arc": CacheARC(runProcessJobs, filesDir, filePath, dirPath, cache); break; case ".aw": filesDir.CopyFile(filePath, mCacheFilesDir, filePath, true); cache.ContainerDirs[dirPath] = ContainerType.AW; break; case ".baa": filesDir.CopyFile(filePath, mCacheFilesDir, filePath, true); break; default: break; } }
private void CopyFile(string src, string destination) { try { _fileSystem.CopyFile(src, destination, true); } catch { } }
public CommandResult Execute(IEnumerable <string> inputParams) { var projectName = inputParams.ElementAtOrDefault(0); var outputMessages = new MessageLines(); // validate project name if (string.IsNullOrEmpty(projectName)) { AppioLogger.Warn(LoggingText.EmptyOpcuaappName); outputMessages.Add(OutputText.OpcuaappPublishFailure, string.Empty); return(new CommandResult(false, outputMessages)); } // build string with publish command source location var projectBuildDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.MesonBuild); var appClientBuildLocation = _fileSystem.CombinePaths(projectBuildDirectory, Constants.ExecutableName.AppClient); var appServerBuildLocation = _fileSystem.CombinePaths(projectBuildDirectory, Constants.ExecutableName.AppServer); // build strings with publish command target location var projectPublishDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.Publish); var appClientPublishLocation = _fileSystem.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppClient); var appServerPublishLocation = _fileSystem.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppServer); // check if any of client and server executables exist if ((string.IsNullOrEmpty(appClientBuildLocation) || !_fileSystem.FileExists(appClientBuildLocation)) && (string.IsNullOrEmpty(appServerBuildLocation) || !_fileSystem.FileExists(appServerBuildLocation))) { AppioLogger.Warn(LoggingText.MissingBuiltOpcuaAppFiles); outputMessages.Add(string.Format(OutputText.OpcuaappPublishFailureMissingExecutables, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // create publish directory _fileSystem.CreateDirectory(projectPublishDirectory); // publish client executable if (!string.IsNullOrEmpty(appClientBuildLocation) && _fileSystem.FileExists(appClientBuildLocation)) { _fileSystem.CopyFile(appClientBuildLocation, appClientPublishLocation); } // publish server executable if (!string.IsNullOrEmpty(appServerBuildLocation) && _fileSystem.FileExists(appServerBuildLocation)) { _fileSystem.CopyFile(appServerBuildLocation, appServerPublishLocation); } // return with success AppioLogger.Info(LoggingText.OpcuaappPublishedSuccess); outputMessages.Add(string.Format(OutputText.OpcuaappPublishSuccess, projectName), string.Empty); return(new CommandResult(true, outputMessages)); }
public void CopyFile_FileIsInBothLocations() { fs.CreateDirectory("/upload/hello"); fs.WriteFile("/upload/hello/world.txt", new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); fs.CreateDirectory("/upload/destination"); fs.CopyFile("/upload/hello/world.txt", "/upload/destination/world.txt"); var from = fs.GetFile("/upload/hello/world.txt"); var to = fs.GetFile("/upload/destination/world.txt"); Assert.That(from, Is.Not.Null); Assert.That(to, Is.Not.Null); }
public void CopyFile_Copies_To_Destination() { // arrange var target = Path.Combine(testFolder, "test-copy.txt"); var srcContent = File.ReadAllText(testFile); // act fileSystem.CopyFile(testFile, target); var tgtContent = File.ReadAllText(target); // assert Assert.True(File.Exists(target)); Assert.Equal(srcContent, tgtContent); }
private bool Copy(string directory, ProjectItem source, ProjectItem destination, ILogger logger) { string absoluteSource = source[Metadatas.FullPath]; string absoluteDestination = destination[Metadatas.FullPath]; string relativeSource = Path.MakeRelative(directory, absoluteSource); string relativeDestination = Path.MakeRelative(directory, absoluteDestination); logger.WriteLine(Verbosity.Normal, " Copying file from \"{0}\" to \"{1}\".", relativeSource, relativeDestination); try { var dir = Path.GetDirectory(absoluteDestination); _fileSystem.CreateDirectory(dir); _fileSystem.CopyFile(absoluteSource, absoluteDestination, true); return(true); } catch (UnauthorizedAccessException e) { LogError(logger, relativeSource, relativeDestination, e); return(false); } catch (IOException e) { LogError(logger, relativeSource, relativeDestination, e); return(false); } }
private void SafeCopy(IPluginDescriptor plugin, IProgressMonitor progressMonitor) { using (progressMonitor.BeginTask(string.Format("Copying {0} plugin", plugin.PluginId), plugin.FilePaths.Count)) { var sourceFolder = Path.Combine(sourcePluginFolder, plugin.RecommendedInstallationPath); var targetFolder = Path.Combine(targetPluginFolder, plugin.RecommendedInstallationPath); foreach (var file in plugin.FilePaths) { var sourceFileInfo = new FileInfo(Path.Combine(sourceFolder, file)); var destination = new FileInfo(Path.Combine(targetFolder, file)); try { if (fileSystem.DirectoryExists(destination.DirectoryName) == false) { fileSystem.CreateDirectory(destination.DirectoryName); } fileSystem.CopyFile(sourceFileInfo.FullName, destination.FullName, true); } catch (Exception ex) { exceptionPolicy.Report(string.Format("Error copying file: {0}", file), ex); } } } }
/// <summary> /// Ensures the list. /// </summary> /// <param name="url">The URL.</param> /// <param name="file">The file.</param> /// <param name="httpClient">The HTTP client.</param> /// <param name="fileSystem">The file system.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> public static async Task <string> EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, CancellationToken cancellationToken) { var fileInfo = fileSystem.GetFileInfo(file); if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1) { var temp = await httpClient.GetTempFile(new HttpRequestOptions { CancellationToken = cancellationToken, Progress = new SimpleProgress <double>(), Url = url }).ConfigureAwait(false); fileSystem.CreateDirectory(fileSystem.GetDirectoryName(file)); try { fileSystem.CopyFile(temp, file, true); } catch { } return(temp); } return(file); }
/// <summary> /// Performs a file modification. /// </summary> /// <param name="sourceFileSystem">The source file system.</param> /// <param name="targetFileSystem">The target file system.</param> /// <param name="sourceFile">The source file.</param> /// <param name="targetDirectory">The target directory.</param> /// <param name="execute">if set to true, the operation gets executed.</param> private void PerformFileModificationOperation(IFileSystem sourceFileSystem, IFileSystem targetFileSystem, IFileInfo sourceFile, IDirectoryInfo targetDirectory, bool execute) { var eventArgs = new FileCopyEventArgs(sourceFile, sourceFile.Directory, targetDirectory); this.OnModifyingFile(eventArgs); if (execute) { EventHandler <DataTransferEventArgs> handler = (sender, e) => { e.Cancel = this.IsStopped; //Stop the copy operation if the job is stopped this.OnFileProgressChanged(e); }; targetFileSystem.FileCopyProgressChanged += handler; try { targetFileSystem.CopyFile(sourceFileSystem, sourceFile, targetDirectory); this.OnModifiedFile(eventArgs); } catch (AccessException) { this.OnFileCopyError(new FileCopyErrorEventArgs(sourceFile, targetDirectory)); } targetFileSystem.FileCopyProgressChanged -= handler; } }
public void CopyTo(string path, CancellationToken token, bool createHardLink) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException("Target path is null or empty."); } if (Stream != null) { using (var fstream = _fs.OpenCreate(path, token)) { Task.Run(async() => await Stream.CopyToAsync(fstream, _uploadBufferSize, token), token).GetAwaiter().GetResult(); } } else { if (createHardLink) { _fs.CreateHardLink(FilePath, path, token); } else { _fs.CopyFile(FilePath, path, token); } } _fs.SetAttributes(path, FileAttributes.Normal, token); }
private object CopyFile(ICommandState state, string source) { // TODO: Run some tests on methods equivalency // to possibly remove code duplication. var folder = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var copyFileName = $"Copy of {fileName}"; var destination = _fileSystem.PathCombine( _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)), new NPath(copyFileName)); while (_fileSystem.FileExists(destination)) { fileName = Path.GetFileName(destination.Raw); copyFileName = $"Copy of {fileName}"; destination = _fileSystem.PathCombine( _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)), new NPath(copyFileName)); } _fileSystem.CopyFile(new NPath(source), destination, true); var fileResult = new { id = destination.Raw, value = copyFileName }; return(fileResult); }
/// <summary> /// Ensures the list. /// </summary> /// <param name="url">The URL.</param> /// <param name="file">The file.</param> /// <param name="httpClient">The HTTP client.</param> /// <param name="fileSystem">The file system.</param> /// <param name="semaphore">The semaphore.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken) { var fileInfo = fileSystem.GetFileInfo(file); if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { var temp = await httpClient.GetTempFile(new HttpRequestOptions { CancellationToken = cancellationToken, Progress = new Progress<double>(), Url = url }).ConfigureAwait(false); fileSystem.CreateDirectory(Path.GetDirectoryName(file)); fileSystem.CopyFile(temp, file, true); } finally { semaphore.Release(); } } }
public static void CopyDirectory(this IFileSystem sourceFileSystem, string sourceDirectory, IFileSystem targetFileSystem, string targetDirectory) { if (!sourceFileSystem.DirectoryExists(sourceDirectory)) { throw new DirectoryNotFoundException($"Could not find source directory at '{sourceDirectory}'"); } if (!targetFileSystem.DirectoryExists(targetDirectory)) { targetFileSystem.CreateDirectory(targetDirectory); } foreach (var file in sourceFileSystem.GetFiles(sourceDirectory, "*", topDirectoryOnly: false)) { var dest = Path.Combine(targetDirectory, GetRelativePath(sourceDirectory, file)); var destDirectory = Path.GetDirectoryName(dest); if (!targetFileSystem.DirectoryExists(destDirectory)) { targetFileSystem.CreateDirectory(destDirectory); } sourceFileSystem.CopyFile(file, dest); } }
private void CacheARC(List <RunProcessJob> runProcessJobs, IFileSystem filesDir, string filePath, string dirPath, Cache cache) { cache.ContainerDirs[filePath] = ContainerType.ARC; mLogger.Information($"Unpacking {filePath}"); // Copy archive to cache (but only if not already in cache) mCacheFilesDir.CreateDirectory(dirPath); if (!mCacheFilesDir.FileExists(filePath)) { filesDir.CopyFile(filePath, mCacheFilesDir, filePath, false); // If the directory the arc is being extracted to is in the same directory as the file itself, delete the original file if (PathHelper.AreInSameDirectory(filePath, dirPath)) { mCacheFilesDir.DeleteFile(filePath); } } // Extract it var process = new Process(); process.StartInfo = new ProcessStartInfo(mConfiguration.ArcExtractPath, Path.GetFullPath(mCacheFilesDir.GetPhysicalPath(filePath))) { RedirectStandardOutput = false, CreateNoWindow = true }; process.Start(); runProcessJobs.Add(new RunProcessJob(process) { TemporaryFiles = { Path.GetFullPath(mCacheFilesDir.GetPhysicalPath(filePath)) } }); }
public static async Task CopyDirectoryAsync(this IFileSystem sourceFileSystem, string sourceDirectory, IFileSystem targetFileSystem, string targetDirectory) { if (!sourceFileSystem.DirectoryExists(sourceDirectory)) { throw new DirectoryNotFoundException($"Could not find source directory at '{sourceDirectory}'"); } if (!targetFileSystem.DirectoryExists(targetDirectory)) { targetFileSystem.CreateDirectory(targetDirectory); } using var directoryLock = new SemaphoreSlim(1); await Task.WhenAll(sourceFileSystem.GetFiles(sourceDirectory, "*", topDirectoryOnly : false).Select(file => { return(Task.Run(async() => { var dest = Path.Combine(targetDirectory, GetRelativePath(sourceDirectory, file)); var destDirectory = Path.GetDirectoryName(dest); if (!targetFileSystem.DirectoryExists(destDirectory)) { await directoryLock.WaitAsync().ConfigureAwait(false); if (!targetFileSystem.DirectoryExists(destDirectory)) { targetFileSystem.CreateDirectory(destDirectory); } directoryLock.Release(); } sourceFileSystem.CopyFile(file, dest); })); })).ConfigureAwait(false); }
/// <summary> /// Ensures the list. /// </summary> /// <param name="url">The URL.</param> /// <param name="file">The file.</param> /// <param name="httpClient">The HTTP client.</param> /// <param name="fileSystem">The file system.</param> /// <param name="semaphore">The semaphore.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken) { var fileInfo = fileSystem.GetFileInfo(file); if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { var temp = await httpClient.GetTempFile(new HttpRequestOptions { CancellationToken = cancellationToken, Progress = new Progress <double>(), Url = url }).ConfigureAwait(false); fileSystem.CreateDirectory(Path.GetDirectoryName(file)); fileSystem.CopyFile(temp, file, true); } finally { semaphore.Release(); } } }
private void CreateOrUpdateFile(CodeFileDisplay file) { // if the file is the root web.config file, save a backup of the original. if (file.VirtualPath.InvariantEndsWith("web.config")) { _fileSystem.CopyFile(file.VirtualPath, $"{file.VirtualPath}.{DateTime.Now:yyyyMMdd-HHmmss}"); } // file.VirtualPath = file.VirtualPath.EnsureCorrectFileExtension(configFileExtension); // file.Name = file.Name.EnsureCorrectFileExtension(configFileExtension); //if (!Path.GetFileNameWithoutExtension(file.VirtualPath).InvariantEquals(Path.GetFileNameWithoutExtension(file.Name))) //{ // _themesFileSystem.DeleteFile(file.VirtualPath); // string[] strArray = file.VirtualPath.Split('/'); // file.VirtualPath = string.Join("/", ((IEnumerable<string>)strArray).Take(strArray.Length - 1)).EnsureEndsWith('/') + file.Name; //} using (MemoryStream memoryStream = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(memoryStream)) { streamWriter.Write(file.Content); streamWriter.Flush(); _fileSystem.AddFile(file.VirtualPath.TrimStart('/'), memoryStream, true); } } }
internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem) { var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); if (fileSystem.FileExists(filePath)) { return filePath; } var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name; var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf"); fileSystem.CreateDirectory(Path.GetDirectoryName(tempPath)); using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath)) { using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.CopyTo(fileStream); } } fileSystem.CreateDirectory(Path.GetDirectoryName(filePath)); try { fileSystem.CopyFile(tempPath, filePath, false); } catch (IOException) { } return tempPath; }
internal static async Task <string> DownloadFont(string name, string url, IApplicationPaths paths, IHttpClient httpClient, IFileSystem fileSystem) { var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); if (fileSystem.FileExists(filePath)) { return(filePath); } var tempPath = await httpClient.GetTempFile(new HttpRequestOptions { Url = url, Progress = new Progress <double>() }).ConfigureAwait(false); fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath)); try { fileSystem.CopyFile(tempPath, filePath, false); } catch (IOException) { } return(tempPath); }
/// <summary> /// Downloads the font file. /// </summary> /// <param name="fontsDirectory">The fonts directory.</param> /// <param name="fontFilename">The font filename.</param> /// <returns>Task.</returns> private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress <double> progress) { var existingFile = Directory .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories) .FirstOrDefault(); if (existingFile != null) { try { _fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true); return; } catch (IOException ex) { // Log this, but don't let it fail the operation _logger.ErrorException("Error copying file", ex); } } string tempFile = null; foreach (var url in _fontUrls) { progress.Report(0); try { tempFile = await _httpClient.GetTempFile(new HttpRequestOptions { Url = url, Progress = progress }).ConfigureAwait(false); break; } catch (Exception ex) { // The core can function without the font file, so handle this _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url); } } if (string.IsNullOrEmpty(tempFile)) { return; } Extract7zArchive(tempFile, fontsDirectory); try { _fileSystem.DeleteFile(tempFile); } catch (IOException ex) { // Log this, but don't let it fail the operation _logger.ErrorException("Error deleting temp file {0}", ex, tempFile); } }
internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem) { var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); if (fileSystem.FileExists(filePath)) { return(filePath); } var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name; var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf"); fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath)); using (var stream = typeof(PlayedIndicatorDrawer).GetTypeInfo().Assembly.GetManifestResourceStream(namespacePath)) { using (var fileStream = fileSystem.GetFileStream(tempPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { stream.CopyTo(fileStream); } } fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath)); try { fileSystem.CopyFile(tempPath, filePath, false); } catch (IOException) { } return(tempPath); }
public async Task <DynamicImageResponse> GetImage(Audio item, List <MediaStream> imageStreams, CancellationToken cancellationToken) { var path = GetAudioImagePath(item); if (!_fileSystem.FileExists(path)) { _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ?? imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ?? imageStreams.FirstOrDefault(); var imageStreamIndex = imageStream == null ? (int?)null : imageStream.Index; var tempFile = await _mediaEncoder.ExtractAudioImage(item.Path, imageStreamIndex, cancellationToken).ConfigureAwait(false); _fileSystem.CopyFile(tempFile, path, true); try { _fileSystem.DeleteFile(tempFile); } catch { } } return(new DynamicImageResponse { HasImage = true, Path = path }); }
void files_FileCopied(object sender, FileEventArgs e) { if (!Enabled) { return; } if (IsResizedPath(e.VirtualPath)) { return; } foreach (ImageSizeElement size in images.Sizes.AllElements) { Url sourceUrl = e.SourcePath; Url destinationUrl = e.VirtualPath; string sourcePath = ImagesUtility.GetResizedPath(sourceUrl, size.Name); if (!files.FileExists(sourcePath)) { continue; } string destinationPath = ImagesUtility.GetResizedPath(destinationUrl, size.Name); if (!files.FileExists(destinationPath)) { files.CopyFile(sourcePath, destinationPath); } } }
private dynamic CopyItem(List <string> items, string singleFileName, string newPath, Dictionary <string, FileService.ReturnMessage> returnMessages, StringBuilder sbErrors) { foreach (string item in items) { OpResult result = OpResult.FileTypeNotAllowed; string file = FilePath(item); if (AllowedExtension(file)) { string newFile = FilePath(newPath + "/" + CleanFileName(singleFileName, "file")); result = fileSystem.CopyFile(file, newFile, overwriteExistingFiles); if (result != OpResult.Succeed) { returnMessages.Add(file, ReturnResult(result)); } } else { returnMessages.Add(file, ReturnResult(result)); } } return(ReturnMessages(returnMessages, sbErrors)); }
public void Should_copy_file() { string srcFileName = CreateTextFile(); string destFileName = GetNewFileName(); _fileSystem.CopyFile(srcFileName, destFileName); AssertFileExists(destFileName); }
private void Process( FileOperation file, bool isMove, SynchronizationContext uiContext, CancellationTokenSource cancellation) { var retry = true; while (retry) { retry = false; try { if (isMove) { _fileSystem.MoveFile(file.SourcePath, file.DestinationPath); } else { _fileSystem.CopyFile(file.SourcePath, file.DestinationPath); } } catch (FileNotFoundException) { // silently ignore this error, just don't copy/move the file } catch (DirectoryNotFoundException) { // silently ignore this error, just don't copy/move the file } catch (IOException) { var result = DialogResult.No; uiContext.Send(_ => { result = _dialogView.ConfirmReplace(file.DestinationPath); }, null); if (result == DialogResult.Yes) { retry = true; _fileSystem.DeleteFile(file.DestinationPath); } else if (result == DialogResult.Cancel) { cancellation.Cancel(); } } catch (UnauthorizedAccessException) { uiContext.Send(_ => _dialogView.UnauthorizedAccess(file.SourcePath), null); } catch (SecurityException) { uiContext.Send(_ => _dialogView.UnauthorizedAccess(file.SourcePath), null); } } }
private void CopyFile(string sourceFile) { try { var targetFile = Path.Combine(_archiveLocation, Path.GetFileName(sourceFile)); _fileSystem.DeleteFileIfExist(targetFile); _fileSystem.CopyFile(sourceFile, targetFile); return; } catch (Exception ex) { Logger.LogError(ex); TryCopyFileWithNewUniueName(sourceFile); } }
public override async Task <string?> OnSetPropertyValueAsync(string propertyName, string unevaluatedPropertyValue, IProjectProperties defaultProperties, IReadOnlyDictionary <string, string>?dimensionalConditions = null) { // Allows the user to clear the application icon. if (string.IsNullOrEmpty(unevaluatedPropertyValue)) { return(null); } // If selected path is invalid, ignore and return previous value. if (!File.Exists(unevaluatedPropertyValue)) { return(await defaultProperties.GetUnevaluatedPropertyValueAsync(propertyName)); } string propertyValue; // Copy the file into the project directory. // This isn't a limitation of ApplicationIcon; it is to simply mimic the legacy property page interaction. if (_unconfiguredProject.IsOutsideProjectDirectory(unevaluatedPropertyValue)) { try { propertyValue = Path.GetFileName(unevaluatedPropertyValue); var destinationInfo = new FileInfo(Path.Combine(Path.GetDirectoryName(_unconfiguredProject.FullPath), propertyValue)); if (destinationInfo.Exists && destinationInfo.IsReadOnly) { // The file cannot be copied over; return the previous value. return(await defaultProperties.GetUnevaluatedPropertyValueAsync(propertyName)); } _fileSystem.CopyFile(unevaluatedPropertyValue, destinationInfo.FullName, overwrite: true); } catch { // If anything goes wrong with trying to copy the file, simply return the previous value. return(await defaultProperties.GetUnevaluatedPropertyValueAsync(propertyName)); } } else { propertyValue = PathHelper.MakeRelative(_unconfiguredProject, unevaluatedPropertyValue); } string existingPropertyValue = await defaultProperties.GetEvaluatedPropertyValueAsync(ConfigurationGeneral.ApplicationIconProperty); IProjectItem?existingItem = await GetExistingContentItemAsync(existingPropertyValue); if (existingItem != null) { await existingItem.SetUnevaluatedIncludeAsync(propertyValue); } else { await _sourceItemsProvider.AddAsync(Content.SchemaName, propertyValue); } return(propertyValue); }
private void PerformFileSorting(MovieFileOrganizationOptions options, FileOrganizationResult result) { // We should probably handle this earlier so that we never even make it this far if (string.Equals(result.OriginalPath, result.TargetPath, StringComparison.OrdinalIgnoreCase)) { return; } _libraryMonitor.ReportFileSystemChangeBeginning(result.TargetPath); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(result.TargetPath)); var targetAlreadyExists = _fileSystem.FileExists(result.TargetPath); try { if (targetAlreadyExists || options.CopyOriginalFile) { _fileSystem.CopyFile(result.OriginalPath, result.TargetPath, true); } else { _fileSystem.MoveFile(result.OriginalPath, result.TargetPath); } result.Status = FileSortingStatus.Success; result.StatusMessage = string.Empty; } catch (Exception ex) { var errorMsg = string.Format("Failed to move file from {0} to {1}: {2}", result.OriginalPath, result.TargetPath, ex.Message); result.Status = FileSortingStatus.Failure; result.StatusMessage = errorMsg; _logger.ErrorException(errorMsg, ex); return; } finally { _libraryMonitor.ReportFileSystemChangeComplete(result.TargetPath, true); } if (targetAlreadyExists && !options.CopyOriginalFile) { try { _fileSystem.DeleteFile(result.OriginalPath); } catch (Exception ex) { _logger.ErrorException("Error deleting file {0}", ex, result.OriginalPath); } } }
internal static async Task<string> DownloadFont(string name, string url, IApplicationPaths paths, IHttpClient httpClient, IFileSystem fileSystem) { var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); if (fileSystem.FileExists(filePath)) { return filePath; } var tempPath = await httpClient.GetTempFile(new HttpRequestOptions { Url = url, Progress = new Progress<double>() }).ConfigureAwait(false); fileSystem.CreateDirectory(Path.GetDirectoryName(filePath)); try { fileSystem.CopyFile(tempPath, filePath, false); } catch (IOException) { } return tempPath; }
/// <summary> /// Performs a file modification. /// </summary> /// <param name="sourceFileSystem">The source file system.</param> /// <param name="targetFileSystem">The target file system.</param> /// <param name="sourceFile">The source file.</param> /// <param name="targetDirectory">The target directory.</param> /// <param name="execute">if set to true, the operation gets executed.</param> private void PerformFileModificationOperation(IFileSystem sourceFileSystem, IFileSystem targetFileSystem, IFileInfo sourceFile, IDirectoryInfo targetDirectory, bool execute) { var eventArgs = new FileCopyEventArgs(sourceFile, sourceFile.Directory, targetDirectory); this.OnModifyingFile(eventArgs); if (execute) { EventHandler<DataTransferEventArgs> handler = (sender, e) => { e.Cancel = this.IsStopped; //Stop the copy operation if the job is stopped this.OnFileProgressChanged(e); }; targetFileSystem.FileCopyProgressChanged += handler; try { targetFileSystem.CopyFile(sourceFileSystem, sourceFile, targetDirectory); this.OnModifiedFile(eventArgs); } catch (AccessException) { this.OnFileCopyError(new FileCopyErrorEventArgs(sourceFile, targetDirectory)); } targetFileSystem.FileCopyProgressChanged -= handler; } }