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; }
public void Setup() { theFileSystem = new FileSystem(); theDirectory = Guid.NewGuid().ToString(); theFileSystem.CreateDirectory(theDirectory); createFile("1.txt"); createFile("2.txt"); createFile("3.txt"); createDirectory("A"); createFile("A", "A1.txt"); createFile("A", "A2.txt"); createFile("A", "A3.txt"); createDirectory("B"); createFile("B", "B1.txt"); createDirectory("C"); createFile("C", "C1.txt"); createFile("C", "C2.txt"); theFileSystem.ForceClean(theDirectory); }
public void Setup() { theFileSystem = new FileSystem(); theDirectory = Path.GetTempPath().AppendRandomPath(); theFileSystem.CreateDirectory(theDirectory); createFile("1.txt"); createFile("2.txt"); createFile("3.txt"); createDirectory("A"); createFile("A", "A1.txt"); createFile("A", "A2.txt"); createFile("A", "A3.txt"); createDirectory("B"); createFile("B", "B1.txt"); createDirectory("C"); createFile("C", "C1.txt"); createFile("C", "C2.txt"); theFileSystem.ForceClean(theDirectory); }
/// <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 void Move(IFileSystem source, FileSystemPath sourcePath, IFileSystem destination, FileSystemPath destinationPath) { bool isFile; if ((isFile = sourcePath.IsFile) != destinationPath.IsFile) throw new ArgumentException("The specified destination-path is of a different type than the source-path."); if (isFile) { using (var sourceStream = source.OpenFile(sourcePath, FileAccess.Read)) { using (var destinationStream = destination.CreateFile(destinationPath)) { byte[] buffer = new byte[BufferSize]; int readBytes; while ((readBytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0) destinationStream.Write(buffer, 0, readBytes); } } source.Delete(sourcePath); } else { destination.CreateDirectory(destinationPath); foreach (var ep in source.GetEntities(sourcePath).ToArray()) { var destinationEntityPath = ep.IsFile ? destinationPath.AppendFile(ep.EntityName) : destinationPath.AppendDirectory(ep.EntityName); Move(source, ep, destination, destinationEntityPath); } if (!sourcePath.IsRoot) source.Delete(sourcePath); } }
public static string CreateNewDirectoryWithRenameAttempts(string directoryName, IFileSystem fileSystem, int maxRenameAttempts) { for (int directoryCreationAttempt = 1; directoryCreationAttempt < maxRenameAttempts; directoryCreationAttempt++) { string numberedDirectoryName; if (directoryCreationAttempt == 1) { numberedDirectoryName = directoryName; } else { string fullPath = Path.GetFullPath(directoryName); string noTrailingSlash; if (fullPath.EndsWith("\\")) { noTrailingSlash = fullPath.Substring(0, fullPath.Length - 1); } else { noTrailingSlash = fullPath; } numberedDirectoryName = string.Format("{0} ({1})", noTrailingSlash, directoryCreationAttempt.ToString()); } if (fileSystem.DirectoryExists(numberedDirectoryName)) { continue; } fileSystem.CreateDirectory(numberedDirectoryName); return numberedDirectoryName; } throw new Exception(string.Format("Could not create directory: {0}. Exceeded {1} attempts.", directoryName, maxRenameAttempts)); }
public JsonLocalizationCache(IHostingEnvironment hostingEnvironment, IFileSystem fileSystem, ILoggerFactory loggerFactory) { _path = hostingEnvironment.MapPath(@"json"); _fileSystem = fileSystem; _logger = loggerFactory.CreateLogger<JsonLocalizationCache>(); _fileSystem.CreateDirectory(_path); _fileSystem.Watch(_path, "*.json", OnChanged); }
public void Execute(IFileSystem fileSystem) { fileSystem.CreateDirectory(this.fullDirectoryPath); foreach (var fileHierarchyNode in this.children) { fileHierarchyNode.Execute(fileSystem); } }
public UacCompliantPaths(IFileSystem fileSystem) { var absoluteDataPath = Environment.ExpandEnvironmentVariables(appFolder); fileSystem.CreateDirectory(absoluteDataPath); Data = absoluteDataPath; Application = AppDomain.CurrentDomain.BaseDirectory; EnureWorkingDirectory(); }
/// <summary> /// Executes the creation of the folder. /// </summary> public void ExecuteCreation(IFileSystem fileSystem) { try { fileSystem.CreateDirectory(_associatedPath); } catch //(DuplicateDirectoryException) { // ADD SOMETHING TO LOG? } }
public void SetUp() { theSolution = new Solution { Directory = "SolutionFiles" }; theFileSystem = new FileSystem(); theFileSystem.CreateDirectory("SolutionFiles"); theSolutionFiles = new SolutionFiles(theFileSystem, new SolutionLoader()); theSolutionFiles.RootDir = Path.GetTempPath().AppendRandomPath(); theFileSystem.CreateDirectory("SolutionFiles", "src"); theFileSystem.CreateDirectory("SolutionFiles", "src", "Project1"); theFileSystem.CreateDirectory("SolutionFiles", "src", "Project2"); theFileSystem.WriteStringToFile(Path.Combine("SolutionFiles", "src", "Project1", "Project1.csproj"), "test"); theFileSystem.WriteStringToFile(Path.Combine("SolutionFiles", "src", "Project2", "Project2.csproj"), "test"); }
public void SetUp() { theSolution = new Solution { Directory = "SolutionFiles" }; theFileSystem = new FileSystem(); theFileSystem.CreateDirectory("SolutionFiles"); theSolutionFiles = new SolutionFiles(theFileSystem, new SolutionLoader()); theSolutionFiles.RootDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SolutionFiles"); theFileSystem.CreateDirectory("SolutionFiles", "src"); theFileSystem.CreateDirectory("SolutionFiles", "src", "Project1"); theFileSystem.CreateDirectory("SolutionFiles", "src", "Project2"); theFileSystem.WriteStringToFile(Path.Combine("SolutionFiles", "src", "Project1", "Project1.csproj"), "test"); theFileSystem.WriteStringToFile(Path.Combine("SolutionFiles", "src", "Project2", "Project2.csproj"), "test"); }
public static void CopyFilesRecursively(DirectoryInfo source, string targetVirtualPath, IFileSystem fs) { foreach (DirectoryInfo dir in source.GetDirectories()) { string newDirVirtualPath = Path.Combine(targetVirtualPath, dir.Name); fs.CreateDirectory(newDirVirtualPath); CopyFilesRecursively(dir, newDirVirtualPath, fs); } foreach (FileInfo file in source.GetFiles()) { fs.WriteFile(Path.Combine(targetVirtualPath, file.Name), file.OpenRead()); } }
public void Copy(IFileSystem source, FileSystemPath sourcePath, IFileSystem destination, FileSystemPath destinationPath) { var pSource = (PhysicalFileSystem)source; var pDestination = (PhysicalFileSystem)destination; var pSourcePath = pSource.GetPhysicalPath(sourcePath); var pDestinationPath = pDestination.GetPhysicalPath(destinationPath); if (sourcePath.IsFile) System.IO.File.Copy(pSourcePath, pDestinationPath); else { destination.CreateDirectory(destinationPath); foreach(var e in source.GetEntities(sourcePath)) source.Copy(e, destination, e.IsFile ? destinationPath.AppendFile(e.EntityName) : destinationPath.AppendDirectory(e.EntityName)); } }
public void Import(IFileSystem fs, Attachment a) { if (a.HasContents) { string path = a.Url; if(!fs.DirectoryExists(Path.GetDirectoryName(path))) { fs.CreateDirectory(Path.GetDirectoryName(path)); } var memoryStream = new MemoryStream(a.FileContents); fs.WriteFile(path, memoryStream); } }
internal static void CopyFolder(this IFileSystem fileSystem, string basePath, string source, string destination) { fileSystem.CreateDirectory(destination); // Copy dirs recursively foreach (var child in Directory.EnumerateDirectories(Path.GetFullPath(Path.Combine(basePath, source))).Select(Path.GetFileName)) { fileSystem.CopyFolder(basePath, Path.Combine(source, child), Path.Combine(destination, child)); } // Copy files foreach (var childFile in Directory.EnumerateFiles(Path.GetFullPath(Path.Combine(basePath, source))).Select(Path.GetFileName)) { fileSystem.CopyFile(Path.Combine(basePath, source, childFile), Path.Combine(destination, childFile)); } }
public void AddUserSchema(XmlSchemaCompletion schema) { if (!fileSystem.DirectoryExists(userDefinedSchemaFolder)) { fileSystem.CreateDirectory(userDefinedSchemaFolder); } string newSchemaDestinationFileName = GetUserDefinedSchemaDestination(schema); fileSystem.CopyFile(schema.FileName, newSchemaDestinationFileName); schema.FileName = newSchemaDestinationFileName; schemas.Add(schema); OnUserDefinedSchemaAdded(); }
public void Run() { RunImpl(); foreach (var entry in Content) { var fileInfo = fileSystem.GetFileInfo(Path.Combine(OutputDirectory, entry.Key)); if (!fileSystem.DirectoryExists(fileInfo.DirectoryPath)) { fileSystem.CreateDirectory(fileInfo.DirectoryPath); } fileSystem.WriteToFile(fileInfo.CompletePath, entry.Value); } }
public static void Copy(this IFileSystem sourceFileSystem, WorkspacePath sourcePath, IFileSystem destinationFileSystem, WorkspacePath destinationPath) { bool isFile; if ((isFile = sourcePath.IsFile) != destinationPath.IsFile) { throw new ArgumentException( "The specified destination-path is of a different type than the source-path."); } if (isFile) { using (var sourceStream = sourceFileSystem.OpenFile(sourcePath, FileAccess.Read)) { using (var destinationStream = destinationFileSystem.CreateFile(destinationPath)) { var buffer = new byte[BufferSize]; int readBytes; while ((readBytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { destinationStream.Write(buffer, 0, readBytes); } } } } else { if (!destinationPath.IsRoot) { destinationFileSystem.CreateDirectory(destinationPath); } foreach (var ep in sourceFileSystem.GetEntities(sourcePath)) { var destinationEntityPath = ep.IsFile ? destinationPath.AppendFile(ep.EntityName) : destinationPath.AppendDirectory(ep.EntityName); Copy(sourceFileSystem, ep, destinationFileSystem, destinationEntityPath); } } // IEntityCopier copier; // if (!EntityCopiers.Registration.TryGetSupported(sourceFileSystem.GetType(), destinationFileSystem.GetType(), // out copier)) // throw new ArgumentException("The specified combination of file-systems is not supported."); // copier.Copy(sourceFileSystem, sourcePath, destinationFileSystem, destinationPath); }
// prepare NuGet dependencies, download them if required private static IEnumerable <string> PreparePackages( string scriptPath, IFileSystem fileSystem, IPackageAssemblyResolver packageAssemblyResolver, IPackageInstaller packageInstaller) { var workingDirectory = Path.GetDirectoryName(scriptPath); var binDirectory = Path.Combine(workingDirectory, @"bin\debug"); //TODO : ScriptCs.Constants.BinFolder var packages = packageAssemblyResolver.GetPackages(workingDirectory); packageInstaller.InstallPackages( packages, allowPreRelease: true); // current implementeation of RoslynCTP required dependencies to be in 'bin' folder if (!fileSystem.DirectoryExists(binDirectory)) { fileSystem.CreateDirectory(binDirectory); } // copy dependencies one by one from 'packages' to 'bin' foreach (var assemblyName in packageAssemblyResolver.GetAssemblyNames(workingDirectory)) { var assemblyFileName = Path.GetFileName(assemblyName); var destFile = Path.Combine(binDirectory, assemblyFileName); var sourceFileLastWriteTime = fileSystem.GetLastWriteTime(assemblyName); var destFileLastWriteTime = fileSystem.GetLastWriteTime(destFile); if (sourceFileLastWriteTime == destFileLastWriteTime) { //outputCallback(string.Format("Skipped: '{0}' because it is already exists", assemblyName)); } else { fileSystem.Copy(assemblyName, destFile, overwrite: true); //if (outputCallback != null) //{ // outputCallback(string.Format("Copy: '{0}' to '{1}'", assemblyName, destFile)); //} } yield return(destFile); } }
/// <summary> /// Saves the image to location. /// </summary> /// <param name="source">The source.</param> /// <param name="path">The path.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken) { _logger.Debug("Saving image to {0}", path); var parentFolder = Path.GetDirectoryName(path); _libraryMonitor.ReportFileSystemChangeBeginning(path); _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder); try { _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); // If the file is currently hidden we'll have to remove that or the save will fail var file = _fileSystem.GetFileInfo(path); // This will fail if the file is hidden if (file.Exists) { if (file.IsHidden) { _fileSystem.SetHidden(file.FullName, false); } if (file.IsReadOnly) { _fileSystem.SetReadOnly(path, false); } } using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) { await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken) .ConfigureAwait(false); } if (_config.Configuration.SaveMetadataHidden) { _fileSystem.SetHidden(file.FullName, true); } } finally { _libraryMonitor.ReportFileSystemChangeComplete(path, false); _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false); } }
// Stores a file at the path relative to the provided destination directory public async Task Store(string relativePath, byte[] fileContent) { var invalidPath = Path.GetInvalidPathChars(); var invalidFile = Path.GetInvalidFileNameChars(); if (Path.DirectorySeparatorChar != '/') { relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar); } if (relativePath.EndsWith(Path.DirectorySeparatorChar.ToString())) { relativePath = Path.Combine(relativePath, "index.html").TrimStart(Path.DirectorySeparatorChar); } var relativePathDirectory = Path.GetDirectoryName(relativePath); var relativePathFile = Path.GetFileName(relativePath); if (!Path.HasExtension(relativePathFile) && !string.IsNullOrEmpty(relativePathFile)) { relativePathFile = Path.ChangeExtension(relativePathFile, "html"); } relativePathDirectory = string.Join('_', relativePathDirectory.Split(Path.GetInvalidPathChars())); relativePathFile = string.Join('_', relativePathFile.Split(Path.GetInvalidFileNameChars())); var fullFilePath = Path.Combine(_destinationDirectory, relativePathDirectory, relativePathFile); var directory = Path.GetDirectoryName(fullFilePath); _fileSystem.CreateDirectory(directory); _logger.LogInformation("Writing {0} to disk", fullFilePath); try { await _fileSystem.WriteFileToDisk(fullFilePath, fileContent); } catch (IOException e) { _logger.LogError("Failed to write {0} to disk, message: {1}", fullFilePath, e.Message); return; } _logger.LogInformation("Done writing {0} to disk", fullFilePath); }
public static void CreateDirectoryRecursive(this IFileSystem fileSystem, FileSystemPath path) { if (!path.IsDirectory) { throw new ArgumentException("The specified path is not a directory."); } var currentDirectoryPath = FileSystemPath.Root; foreach (var dirName in path.GetDirectorySegments()) { currentDirectoryPath = currentDirectoryPath.AppendDirectory(dirName); if (!fileSystem.Exists(currentDirectoryPath)) { fileSystem.CreateDirectory(currentDirectoryPath); } } }
public void RenameDirectory_EntriesAreMoved() { IFileSystem fs = CreateFileSystem(); fs.CreateDirectory("/dir1".ToU8Span()); Result rcRename = fs.RenameDirectory("/dir1".ToU8Span(), "/dir2".ToU8Span()); Result rcDir2 = fs.GetEntryType(out DirectoryEntryType dir2Type, "/dir2".ToU8Span()); Result rcDir1 = fs.GetEntryType(out _, "/dir1".ToU8Span()); Assert.Success(rcRename); Assert.Success(rcDir2); Assert.Equal(DirectoryEntryType.Directory, dir2Type); Assert.Result(ResultFs.PathNotFound, rcDir1); }
private void UpdateList(List <T> newList) { if (newList == null) { throw new ArgumentNullException("newList"); } var file = _dataPath + ".json"; _fileSystem.CreateDirectory(Path.GetDirectoryName(file)); lock (_fileDataLock) { _jsonSerializer.SerializeToFile(newList, file); _items = newList; } }
/// <summary> /// Try to load all query views from the query view directory (specified in user settings). /// If this operation fails, an error message is shown to the user. /// </summary> /// <param name="path">Path to the query views directory</param> private void LoadQueryViews(string path) { try { var files = _fileSystem.EnumerateFiles(path, "*.vql"); foreach (var file in files) { var name = Path.GetFileNameWithoutExtension(file); var content = _fileSystem.ReadAllText(file); _queryViews.Add(new QueryView(name, content, file)); } } catch (DirectoryNotFoundException) { _fileSystem.CreateDirectory(path); } }
public void Log(Exception ex) { _logger.ErrorException("UnhandledException", ex); _logManager.Flush(); var path = Path.Combine(_appPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt"); _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); var builder = LogHelper.GetLogMessage(ex); // Write to console just in case file logging fails _console.WriteLine("UnhandledException"); _console.WriteLine(builder.ToString()); _fileSystem.WriteAllText(path, builder.ToString()); }
/// <summary> /// Downloads the movie info. /// </summary> /// <param name="id">The id.</param> /// <param name="preferredMetadataLanguage">The preferred metadata language.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> internal async Task <CompleteMovieData> DownloadMovieInfo(string id, string preferredMetadataLanguage, string preferredMetadataCountry, CancellationToken cancellationToken) { var mainResult = await FetchMainResult(id, true, preferredMetadataLanguage, preferredMetadataCountry, cancellationToken).ConfigureAwait(false); if (mainResult == null) { return(null); } var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath)); _jsonSerializer.SerializeToFile(mainResult, dataFilePath); return(mainResult); }
protected virtual void WriteXmlFile(string objectName, string xml) { Throw.If(objectName).IsEmpty(); if (xml != null) { xml = xml.Trim(); } if (string.IsNullOrEmpty(xml)) { messageManager.OnScriptMessage(string.Format("{0} is empty.", objectName)); } else { string dir = Path.Combine(exportDirectory, "Data"); string scriptPath = Path.Combine(dir, objectName + ".xml"); try { if (!fileSystem.Exists(dir)) { fileSystem.CreateDirectory(dir); } if (fileSystem.Exists(scriptPath)) { fileSystem.SetFileAttributes(scriptPath, FileAttributes.Normal); } using (TextWriter scriptFile = fileSystem.OpenFileForWriting(scriptPath)) { scriptFile.WriteLine(xml); } } catch (Exception ex) { string msg = string.Format("Could not write the xml file {0} to disk.", scriptPath); throw new SqlMigrationException(msg, ex); } messageManager.OnScriptMessage(scriptPath); } }
public async Task <DynamicImageResponse> GetImage(Audio item, List <MediaStream> imageStreams, CancellationToken cancellationToken) { var path = GetAudioImagePath(item); if (!_fileSystem.FileExists(path)) { var semaphore = GetLock(path); // Acquire a lock await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { // Check again in case it was saved while waiting for the lock if (!_fileSystem.FileExists(path)) { _fileSystem.CreateDirectory(Path.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; using (var stream = await _mediaEncoder.ExtractAudioImage(item.Path, imageStreamIndex, cancellationToken).ConfigureAwait(false)) { using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { await stream.CopyToAsync(fileStream).ConfigureAwait(false); } } } } finally { semaphore.Release(); } } return(new DynamicImageResponse { HasImage = true, Path = path }); }
public void Move(IFileSystem source, FileSystemPath sourcePath, IFileSystem destination, FileSystemPath destinationPath) { bool isFile; if ((isFile = sourcePath.IsFile) != destinationPath.IsFile) { throw new ArgumentException( "The specified destination-path is of a different type than the source-path."); } if (isFile) { using (var sourceStream = source.OpenFile(sourcePath, FileAccess.Read)) { using (var destinationStream = destination.CreateFile(destinationPath)) { var buffer = new byte[BufferSize]; int readBytes; while ((readBytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { destinationStream.Write(buffer, 0, readBytes); } } } source.Delete(sourcePath); } else { destination.CreateDirectory(destinationPath); foreach (var ep in source.GetEntities(sourcePath).ToArray()) { var destinationEntityPath = ep.IsFile ? destinationPath.AppendFile(ep.EntityName) : destinationPath.AppendDirectory(ep.EntityName); Move(source, ep, destination, destinationEntityPath); } if (!sourcePath.IsRoot) { source.Delete(sourcePath); } } }
/// <summary> /// Ensures that the target <see cref="worldDataPathRoot"/> exists and /// the file system is writable. /// </summary> /// <exception cref="Exception"> /// Is thrown when checking the directory existance or creating a /// non-existant directory fails or when the file system is read-only. /// </exception> private void ProbeSaveDirectory() { try { lock (fileSystemLock) { if (!userDataFileSystem.ExistsDirectory(worldDataPathRoot)) { userDataFileSystem.CreateDirectory(worldDataPathRoot); } } } catch (Exception exc) { throw new Exception("The save directory couldn't be accessed.", exc); } }
public static Project Create(string projectDir, string name) { FileSystem.CreateDirectory(projectDir); var stream = typeof(SolutionGraphScenario) .Assembly .GetManifestResourceStream("{0}.ProjectTemplate.txt".ToFormat(typeof(SolutionGraphScenario).Namespace)); var projectFile = Path.Combine(projectDir, RippleDependencyStrategy.RippleDependenciesConfig); FileSystem.WriteStringToFile(projectFile, ""); var csProjectFile = Path.Combine(projectDir, "{0}.csproj".ToFormat(name)); FileSystem.WriteStreamToFile(csProjectFile, stream); return(new Project(csProjectFile)); }
internal async Task EnsurePersonInfo(string doubanId, CancellationToken cancellationToken) { _logger.Info("EnsurePersonInfo" + doubanId); var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, doubanId); var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath); if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2) { return; } var result = await getPersonInfo(doubanId, cancellationToken); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath)); System.IO.File.WriteAllText(dataFilePath, _jsonSerializer.SerializeToString(result)); }
private void writeFile(string outputFile, IEnumerable <string> sourceFiles, string separatorFormat) { Debug.WriteLine("generating combined file: " + outputFile); _fileSystem.CreateDirectory(Path.GetDirectoryName(outputFile)); using (var output = File.CreateText(outputFile)) { foreach (var sourceFile in sourceFiles) { var readAllText = File.ReadAllText(sourceFile); if (separatorFormat != null) { var separator = separatorFormat.ToFormat(Path.GetFileName(sourceFile)); output.WriteLine(separator); } output.WriteLine(readAllText); } } }
/// <summary> /// Extracts all files to the given directory /// </summary> /// <param name="outputDirectory">Directory to which the files should be saved. This will be created if it does not exist.</param> /// <param name="fileSystem">File system to which to save the files</param> public async Task Extract(string outputDirectory, IFileSystem fileSystem, ProgressReportToken?progressReportToken = null) { if (!fileSystem.DirectoryExists(outputDirectory)) { fileSystem.CreateDirectory(outputDirectory); } var filenames = GetFilenames(); await AsyncFor.ForEach(filenames, filename => { var fileData = GetFile(filename); if (fileData == null) { return; } fileSystem.WriteAllBytes(Path.Combine(outputDirectory, filename), fileData); }, progressReportToken : progressReportToken).ConfigureAwait(false); }
private void TestWebp() { try { var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp"); _fileSystem.CreateDirectory(Path.GetDirectoryName(tmpPath)); using (var wand = new MagickWand(1, 1, new PixelWand("none", 1))) { wand.SaveImage(tmpPath); } } catch { //_logger.ErrorException("Error loading webp: ", ex); _webpAvailable = false; } }
private void SaveId(string id) { try { var path = CachePath; _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); lock (_syncLock) { _fileSystem.WriteAllText(path, id, Encoding.UTF8); } } catch (Exception ex) { _logger.LogError(ex, "Error writing to file"); } }
public override bool UpdateItem(ContentItem item, Control editor) { SelectingUploadCompositeControl composite = (SelectingUploadCompositeControl)editor; HttpPostedFile postedFile = composite.UploadControl.PostedFile; if (postedFile != null && !string.IsNullOrEmpty(postedFile.FileName)) { IFileSystem fs = Engine.Resolve <IFileSystem>(); string directoryPath; if (uploadDirectory == string.Empty) { directoryPath = Engine.Resolve <IDefaultDirectory>().GetDefaultDirectory(item); } else { directoryPath = uploadDirectory; } if (!fs.DirectoryExists(directoryPath)) { fs.CreateDirectory(directoryPath); } string fileName = Path.GetFileName(postedFile.FileName); fileName = Regex.Replace(fileName, InvalidCharactersExpression, "-"); string filePath = VirtualPathUtility.Combine(directoryPath, fileName); fs.WriteFile(filePath, postedFile.InputStream); item[Name] = Url.ToAbsolute(filePath); return(true); } if (composite.SelectorControl.Url != item[Name] as string) { item[Name] = composite.SelectorControl.Url; return(true); } return(false); }
public Solution Build() { var solution = _files.LoadSolution(); _files.ForProjects(solution, x => { var project = _project.Read(x); solution.AddProject(project); }); solution.EachProject(project => { if (!project.HasProjFile()) { return; } var references = project.Proj.ProjectReferences; references.Each(r => { var name = r.ProjectName; if (name.Contains(" ")) { name = name.Split(' ').First(); } var projectRef = solution.FindProject(name); if (projectRef != null) { project.AddProjectReference(projectRef); } }); }); solution.UseStorage(NugetStorage.For(solution.Mode)); _fileSystem.CreateDirectory(solution.PackagesDirectory()); _files.FinalizeSolution(solution); solution.Dependencies.MarkRead(); return(solution); }
public void ConfigureAutoRun(bool autorun) { var shortcutPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.StartMenu), "Emby", "Emby Server.lnk"); var startupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup); if (autorun) { //Copy our shortut into the startup folder for this user var targetPath = Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk"); _fileSystem.CreateDirectory(Path.GetDirectoryName(targetPath)); File.Copy(shortcutPath, targetPath, true); } else { //Remove our shortcut from the startup folder for this user _fileSystem.DeleteFile(Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk")); } }
private void WriteDirectoryCreate(HttpContext context) { ValidateTicket(context.Request["ticket"]); FS = Engine.Resolve <IFileSystem>(); var parentDirectory = context.Request["selected"]; var selected = new Directory(DirectoryData.Virtual(parentDirectory), null); if (string.IsNullOrEmpty(parentDirectory) || !Engine.SecurityManager.IsAuthorized(context.User, selected, N2.Security.Permission.Write)) { context.Response.WriteJson(new { Status = "Error", Message = "Not allowed" }); return; } var name = context.Request["name"]; if (string.IsNullOrWhiteSpace(name)) { context.Response.WriteJson(new { Status = "Error", Message = "Directory name required" }); return; } var newDir = VirtualPathUtility.AppendTrailingSlash(context.Request.ApplicationPath + selected.Url) + name; try { if (FS.DirectoryExists(newDir)) { context.Response.WriteJson(new { Status = "Exists", Message = "Directory already exists" }); } else { FS.CreateDirectory(newDir); context.Response.WriteJson(new { Status = "Ok", Message = "Directory created" }); } return; } catch (Exception e) { context.Response.WriteJson(new { Status = "Error", Message = "Create directory failed", Detail = e.Message }); return; } }
public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file) { var device = GetDevice(deviceId); var path = GetUploadPath(device); if (!string.IsNullOrWhiteSpace(file.Album)) { path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album)); } path = Path.Combine(path, file.Name); path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg"); _libraryMonitor.ReportFileSystemChangeBeginning(path); _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); try { using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { await stream.CopyToAsync(fs).ConfigureAwait(false); } _repo.AddCameraUpload(deviceId, file); } finally { _libraryMonitor.ReportFileSystemChangeComplete(path, true); } if (CameraImageUploaded != null) { EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo> { Argument = new CameraImageUploadInfo { Device = device, FileInfo = file } }, _logger); } }
public void Copy(IFileSystem srcFileSystem, IFileSystem destFileSystem, string srcFilePath, string destFilePath) { if (srcFileSystem == null) { throw new ArgumentNullException(nameof(srcFileSystem)); } if (destFileSystem == null) { throw new ArgumentNullException(nameof(destFileSystem)); } if (srcFilePath == null) { throw new ArgumentNullException(nameof(srcFilePath)); } if (destFilePath == null) { throw new ArgumentNullException(nameof(destFilePath)); } if (srcFilePath.EndsWith(TempExtenstion)) { return; } try { var tempFilePath = srcFilePath + TempExtenstion; destFileSystem.CreateDirectory(Path.GetDirectoryName(srcFilePath)); srcFileSystem.CopyFile(srcFilePath, destFileSystem, tempFilePath, true); _logger.LogTrace($"Copied file from source {srcFilePath} to temp {tempFilePath}."); destFileSystem.MoveFile(tempFilePath, destFilePath, true); _logger.LogTrace($"Moved file from source {srcFilePath} to dest {destFilePath} successfully."); _fileComparer.EnsureIsEqualFile(srcFileSystem, destFileSystem, srcFilePath, destFilePath); } catch (Exception e) { _logger.LogError(e.GetBaseException().ToString()); } }
/// <summary> /// Generates SQL scripts for the deployment of R code into SQL database. /// Writes scripts to files and pushes files into the target database project. /// </summary> public void Generate(SqlSProcPublishSettings settings, IEnumerable <string> sprocFiles, EnvDTE.Project targetProject) { var targetFolder = Path.Combine(Path.GetDirectoryName(targetProject.FullName), "R\\"); if (!_fs.DirectoryExists(targetFolder)) { _fs.CreateDirectory(targetFolder); } var targetProjectItem = targetProject.ProjectItems.Item("R") ?? targetProject.ProjectItems.AddFolder("R"); var sprocMap = CreateStoredProcedureFiles(settings, sprocFiles, targetFolder, targetProjectItem); if (settings.CodePlacement == RCodePlacement.Table) { CreateRCodeTableFile(settings, targetProject, targetFolder, targetProjectItem); CreatePostDeploymentScriptFile(settings, targetProject, targetFolder, targetProjectItem, sprocMap); } }
private static Config LoadConfig(IConfigLoader configLoader, IFileSystem fileSystem) { var config = configLoader.Load<Config>("ChatLog/Config.json") ?? new Config(); if (string.IsNullOrWhiteSpace(config.Path)) { config.Path = "ChatLogs"; Log.Info("No path specified, using 'ChatLogs'"); } else { config.Path = config.Path; } try { if (fileSystem.DirectoryExists(config.Path)) { Log.Info("Path exists, skipping creation"); } else { Log.Info("Path does not exist, creating it.."); fileSystem.CreateDirectory(config.Path); } Log.Info($"Path is '{config.Path}'"); } catch (Exception e) { Log.Error($"Error creating '{config.Path}': {e.Message}"); Log.Error("Path not set"); } return config; }
// prepare NuGet dependencies, download them if required private static IEnumerable<string> PreparePackages( string scriptPath, IFileSystem fileSystem, IPackageAssemblyResolver packageAssemblyResolver, IPackageInstaller packageInstaller) { var workingDirectory = Path.GetDirectoryName(scriptPath); var binDirectory = Path.Combine(workingDirectory, @"bin\debug"); //TODO : ScriptCs.Constants.BinFolder var packages = packageAssemblyResolver.GetPackages(workingDirectory); packageInstaller.InstallPackages( packages, allowPreRelease: true); // current implementeation of RoslynCTP required dependencies to be in 'bin' folder if (!fileSystem.DirectoryExists(binDirectory)) { fileSystem.CreateDirectory(binDirectory); } // copy dependencies one by one from 'packages' to 'bin' foreach (var assemblyName in packageAssemblyResolver.GetAssemblyNames(workingDirectory)) { var assemblyFileName = Path.GetFileName(assemblyName); var destFile = Path.Combine(binDirectory, assemblyFileName); var sourceFileLastWriteTime = fileSystem.GetLastWriteTime(assemblyName); var destFileLastWriteTime = fileSystem.GetLastWriteTime(destFile); if (sourceFileLastWriteTime == destFileLastWriteTime) { //outputCallback(string.Format("Skipped: '{0}' because it is already exists", assemblyName)); } else { fileSystem.Copy(assemblyName, destFile, overwrite: true); //if (outputCallback != null) //{ // outputCallback(string.Format("Copy: '{0}' to '{1}'", assemblyName, destFile)); //} } yield return destFile; } }
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; }
private string CreateTempTestDir(IFileSystem fileSystem) { if (!fileSystem.DirectoryExists(TestConstants.TempDirectory)) { fileSystem.CreateDirectory(TestConstants.TempDirectory); } return TestConstants.TempDirectory; }
static bool EnsureVersionAssemblyInfoFile(Arguments arguments, IFileSystem fileSystem, string fullPath) { if (fileSystem.Exists(fullPath)) return true; if (!arguments.EnsureAssemblyInfo) return false; var assemblyInfoSource = AssemblyVersionInfoTemplates.GetAssemblyInfoTemplateFor(fullPath); if (!string.IsNullOrWhiteSpace(assemblyInfoSource)) { var fileInfo = new FileInfo(fullPath); if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName)) { fileSystem.CreateDirectory(fileInfo.Directory.FullName); } fileSystem.WriteAllText(fullPath, assemblyInfoSource); return true; } Logger.WriteWarning(string.Format("No version assembly info template available to create source file '{0}'", arguments.UpdateAssemblyInfoFileName)); return false; }
public void SetUp() { _fileSystem = new FileSystem(); _fileSystem.CreateDirectory("deep".AppendPath("a","b","c")); _fileSystem.CreateDirectory("deep".AppendPath("config")); }
public msbuild_builder() { _fileSystem = new InMemoryFileSystem(); rootPath = _fileSystem.CreateDirectory("testdir"); }
public Searching_up_the_tree_for_a_dir() { _testDirectory = new TestDirectory(); _testDirectory.ChangeDirectory(); _fileSystem = new FileSystem(); _fileSystem.CreateDirectory("deep".AppendPath("a", "b", "c")); _fileSystem.CreateDirectory("deep".AppendPath("config")); }
static async Task<IFile> CopyDirectoryAsync (this IFileSystem src, IFile file, IFileSystem dest, string destDir) { var newPath = await dest.GetAvailableNameAsync (Path.Combine (destDir, Path.GetFileName (file.Path))); var r = await dest.CreateDirectory (newPath); if (!r) throw new Exception ("Failed to create destination directory " + newPath + " on " + dest); var srcFiles = await src.ListFiles (file.Path); foreach (var f in srcFiles) { await src.CopyAsync (f, dest, newPath); } try { return await dest.GetFile (newPath); } catch (Exception ex) { Log.Error (ex); return null; } }
/// <summary> /// Performs a directory creation. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="sourceDirectory">The source directory.</param> /// <param name="targetDirectory">The target directory.</param> /// <param name="execute">if set to true, the operation gets executed.</param> private void PerformDirectoryCreationOperation(IFileSystem fileSystem, IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory, bool execute) { var eventArgs = new DirectoryCreationEventArgs(sourceDirectory, targetDirectory); this.OnCreatingDirectory(eventArgs); if (execute) { try { fileSystem.CreateDirectory(sourceDirectory, targetDirectory); this.OnCreatedDirectory(eventArgs); } catch (AccessException) { this.excludedPaths.Add(NormalizePath(targetDirectory.FullName)); this.OnDirectoryCreationError(new DirectoryCreationEventArgs(sourceDirectory, targetDirectory)); } } }
public SolutionExpression(ISolutionGraphScenarioBuilder builder, string name) { _fileSystem = new FileSystem(); var solutionDir = Path.Combine(builder.Directory, name); _fileSystem.CreateDirectory(solutionDir); var solutionFile = Path.Combine(solutionDir, SolutionFiles.ConfigFile); _fileSystem.WriteStringToFile(solutionFile, ""); _solution = new Solution { Name = name, Path = solutionFile }; _solution.Directory = solutionDir; _solution.SourceFolder = Path.Combine(solutionDir, "src"); _solution.NugetSpecFolder = Path.Combine(solutionDir, "packaging", "nuget"); _fileSystem.CreateDirectory(_solution.SourceFolder); builder.AddSolution(_solution); _builder = builder; _projects = new Cache<string, Project>(createAndAddProject); addDefaultProject(); }