public bool AddRSSInfo(RSSViewModel vm) { //pubdate format from http://www.dotnetperls.com/pubdate IFileProvider provider = _appEnvironment.ContentRootFileProvider; IDirectoryContents contents = provider.GetDirectoryContents("wwwroot\\content"); if (!contents.Any(c => c.Name == "feed.xml")) { if (!CreateXMLFile()) { return(false); } } XDocument xdoc; DateTime now = DateTime.Now; if (!XmlFilePopulated()) { xdoc = new XDocument( new XElement("rss", new XAttribute("version", "2.0"), new XElement("channel", new XElement("title", vm.Title), new XElement("description", vm.Description), new XElement("link", vm.Link), new XElement("pubDate", now.ToString("ddd',' d MMM yyyy HH':'mm':'ss") + " " + now.ToString("zzzz").Replace(":", "")), new XElement("lastBuildDate", now.ToString("ddd',' d MMM yyyy HH':'mm':'ss") + " " + now.ToString("zzzz").Replace(":", "")), new XElement("ttl", vm.TimeToLive)))); } else { xdoc = XDocument.Load(contents.Where(c => c.Name == "feed.xml").FirstOrDefault().CreateReadStream()); xdoc.Descendants("title").FirstOrDefault()?.SetValue(vm.Title); xdoc.Descendants("description").FirstOrDefault()?.SetValue(vm.Description); xdoc.Descendants("link").FirstOrDefault()?.SetValue(vm.Link); xdoc.Descendants("lastBuildDate").FirstOrDefault()?.SetValue(now.ToString("ddd',' d MMM yyyy HH':'mm':'ss") + " " + now.ToString("zzzz").Replace(":", "")); xdoc.Descendants("ttl").FirstOrDefault()?.SetValue(vm.TimeToLive); } try { using (var fileStream = new FileStream(_appEnvironment.ContentRootPath + "\\wwwroot\\content\\feed.xml", FileMode.Create)) { xdoc.Save(fileStream); } } catch (Exception e) { return(false); } return(true); }
private IEnumerable <RazorProjectItem> EnumerateFiles(IDirectoryContents directory, string basePath, string prefix) { if (directory.Exists) { foreach (var fileInfo in directory) { if (fileInfo.IsDirectory) { var relativePath = prefix + "/" + fileInfo.Name; var subDirectory = FileProvider.GetDirectoryContents(JoinPath(basePath, relativePath)); var children = EnumerateFiles(subDirectory, basePath, relativePath); foreach (var child in children) { yield return(child); } } else if (string.Equals(RazorFileExtension, Path.GetExtension(fileInfo.Name), StringComparison.OrdinalIgnoreCase)) { var filePath = prefix + "/" + fileInfo.Name; yield return(new FileProviderRazorProjectItem(fileInfo, basePath, filePath: filePath, root: _hostingEnvironment.ContentRootPath)); } } } }
private IEnumerable <RazorProjectItem> EnumerateFiles(IDirectoryContents directory, string basePath, string prefix) { if (directory.Exists) { foreach (var file in directory) { if (file.IsDirectory) { var relativePath = prefix + "/" + file.Name; var subDirectory = _provider.GetDirectoryContents(JoinPath(basePath, relativePath)); var children = EnumerateFiles(subDirectory, basePath, relativePath); foreach (var child in children) { yield return(child); } } else if (string.Equals(RazorFileExtension, Path.GetExtension(file.Name), StringComparison.OrdinalIgnoreCase)) { var filePath = prefix + "/" + file.Name; var absoluteBasePath = _hostingEnvironment.ContentRootPath; var relativePhysicalPath = file.PhysicalPath?.Substring(absoluteBasePath.Length + 1); // Include leading separator relativePhysicalPath = relativePhysicalPath ?? filePath; // Use the incoming path if the file is not directly accessible yield return(new FileProviderRazorProjectItem(file, basePath, filePath: filePath, relativePhysicalPath: relativePhysicalPath)); } } } }
private bool TryGetDirectoryInfo(ILibrary library, PathString subpath, out IDirectoryContents contents) { var fileProvider = new PhysicalFileProvider(library.Path); contents = fileProvider.GetDirectoryContents(subpath.Value); return(contents.Exists); }
// TODO: This is a debug function that allows me to pull a predefined JSON file. Need to find out how to get the physical path. string getJSONFromFile() { string jsonToReturn = "No file to return"; string rootPath = environment.ContentRootPath; var fileProvider = new PhysicalFileProvider(rootPath); IDirectoryContents files = fileProvider.GetDirectoryContents("wwwroot"); IFileInfo fileInfo = fileProvider.GetFileInfo("sampleUpdate.json"); if (fileInfo.Exists) { StreamReader reader = null; try { reader = new StreamReader(fileInfo.CreateReadStream()); jsonToReturn = reader.ReadToEnd(); } catch (Exception ex) { jsonToReturn = ex.Message; } finally { reader.Close(); } } return(jsonToReturn); }
private IEnumerable <FileInfo> scanRecursively(string path, string parentId) { List <FileInfo> files = new List <FileInfo>(); IDirectoryContents contents = fileProvider.GetDirectoryContents(path); foreach (IFileInfo fi in contents) { if (fi.Exists) { string id = System.Guid.NewGuid().ToString(); FileInfo f = FileInfo.Parse(fi, id, parentId); if (fi.IsDirectory) { List <FileInfo> children = new List <FileInfo>(); string dirName = fi.Name; children.AddRange(scanRecursively(path + dirName + "/", id)); // recursively scan children f.Children = children.Where(child => child.Parent.Equals(id)).Select(child => child.Id).ToArray(); files.AddRange(children); } files.Add(f); } } return(files); }
public IActionResult FileTreeFolders(string dir) { if (string.IsNullOrEmpty(dir)) { dir = "/"; } if (!dir.StartsWith(LyniconSystem.Instance.Settings.FileManagerRoot)) { return(new HttpStatusCodeResult(403, "Cannot access this directory")); } IDirectoryContents di = hosting.WebRootFileProvider.GetDirectoryContents(dir); var output = di .Where(fi => fi.IsDirectory) .OrderBy(cdi => cdi.Name) .Select(cdi => new { data = new { title = cdi.Name }, state = "closed", attr = new { title = dir + cdi.Name + "/" } }).ToArray(); return(Json(output)); }
public IActionResult FileTreeFiles(string dir) { if (string.IsNullOrEmpty(dir)) { dir = "/"; } if (!dir.StartsWith(LyniconSystem.Instance.Settings.FileManagerRoot)) { return(new HttpStatusCodeResult(403, "Cannot access this directory")); } IDirectoryContents di = hosting.WebRootFileProvider.GetDirectoryContents(dir); var output = new { dir = !di.Exists ? null : dir + (dir[dir.Length - 1] == '/' ? "" : "/"), dirs = !di.Exists ? null : di.Where(fi => fi.IsDirectory) .OrderBy(cdi => cdi.Name) .Select(cdi => new { name = cdi.Name }).ToArray(), files = !di.Exists ? null : di.Where(fi => !fi.IsDirectory) .OrderBy(cfi => cfi.Name) .Select(cfi => new { name = cfi.Name, ext = cfi.Name.LastAfter("."), size = cfi.Length }).OrderBy(inf => inf.name).ToArray() }; return(Json(output)); }
public static IFileInfo GetContentFileInfo(this PathString path, IFileProvider fileProvider) { string rPath = (path == null || !path.HasValue || path.Value == "") ? "/" : path.Value; IFileInfo fileInfo = null; try { fileInfo = fileProvider.GetFileInfo(rPath); if (fileInfo == null) { fileInfo = new NotFoundFileInfo(rPath); } else if (fileInfo.Exists) { if (!fileInfo.IsDirectory) { return(fileInfo); } IDirectoryContents contents = fileProvider.GetDirectoryContents(rPath); IFileInfo page = DefaultPageNames.Select(p => contents.FirstOrDefault(c => String.Equals(p, c.Name, StringComparison.InvariantCultureIgnoreCase))) .FirstOrDefault(f => f != null); if (page != null) { fileInfo = page; } } } catch (Exception exception) { fileInfo = new GetFileError(rPath, exception); } return(fileInfo); }
/* * Initializes the "database" list of cities. Only done once. */ private void InitializeLocationList() { IFileProvider provider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); IDirectoryContents contents = provider.GetDirectoryContents(""); // Application root IFileInfo fileInfo = provider.GetFileInfo(CITY_INFORMATION_FILE_NAME); LocationInfo location; foreach (var line in File.ReadLines(fileInfo.Name).Skip(1)) { var currentLine = line.Split('\t'); long id = Convert.ToInt64(currentLine[0]); string name = currentLine[1]; float latitude = float.Parse(currentLine[4]); float longitude = float.Parse(currentLine[5]); string country = currentLine[8]; string provinceStateCode = String.Empty; if (int.TryParse(currentLine[10], out int fips)) { provinceStateCode = ((Province)fips).ToString(); } else { provinceStateCode = currentLine[10]; } long population = long.Parse(currentLine[14]); location = new LocationInfo(name, latitude, longitude, country, provinceStateCode, population); locationDb.Add(id, location); } }
protected IEnumerable <IFileInfo> FindMeshes(IDirectoryContents directory) { var inSubDirs = directory.OfType <DirectoryInfo>().Bind(d => FindMeshes(d.Contents)); var inCurrentDir = directory.Filter(f => !f.IsDirectory && f.Name.EndsWith(".mesh")); return(inCurrentDir.Concat(inSubDirs)); }
public static RecipeBook CreateFromRecipeFolder(IDirectoryContents folder) { var b = new RecipeBook { Recipes = new List <Recipe>() }; foreach (var file in folder) { if (file.Name.EndsWith(".txt")) { using (var s = file.CreateReadStream()) using (var r = new StreamReader(s, Encoding.UTF8)) { var lines = new List <string>(); string line; while ((line = r.ReadLine()) != null) { lines.Add(line); } b.Recipes.Add(CreateFromFileLines(lines, Path.GetFileNameWithoutExtension(file.Name))); } } } b.Tags = b.Recipes.SelectMany(x => x.Tags).Distinct().OrderBy(x => x).ToList(); return(b); }
#pragma warning disable CS1998 void ScanDirAndRegisterFiles(string dir) { if (this.IsDirectoryExistsImplAsync(dir)._GetResult() == false) { this.CreateDirectoryImplAsync(dir)._GetResult(); } IDirectoryContents entityList = Provider.GetDirectoryContents(dir); foreach (IFileInfo entity in entityList) { if (entity.Exists) { if (entity.IsDirectory) { string subDirFullPath = PathParser.Mac.Combine(dir, entity.Name); ScanDirAndRegisterFiles(subDirFullPath); } else { string fileFullPath = PathParser.Mac.Combine(dir, entity.Name); using (this.AddFileAsync(new FileParameters(fileFullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite), async(newFilename, newFileOption, c) => { return(new VfsFileProviderBasedFile(this, entity, newFilename)); })._GetResult()) { } } } } }
public static ApiDirectory GetDirectoryInfo(IDirectoryContents directory, string relativePathToDirectory) { var subdir = new List <string>(); var files = new List <ApiFile>(); foreach (var file in directory) { if (file.IsDirectory) { subdir.Add(file.Name); } else { files.Add(new ApiFile() { Name = file.Name, SizeBytes = file.Length, DateModified = file.LastModified.DateTime, DateCreated = File.GetCreationTimeUtc(file.PhysicalPath) }); } } var apiDirectory = new ApiDirectory() { Name = Path.GetFileName(relativePathToDirectory), RelativePath = relativePathToDirectory, SubDirectories = subdir, Files = files }; return(apiDirectory); }
IFileInfo[] GetFiles() { IDirectoryContents dir = packageProvider.FileProvider.GetDirectoryContents(null); IFileInfo[] files = dir.ToArray(); // Convert package entries to package file infos for (int i = 0; i < files.Length; i++) { // Get file reference string filename = files[i].Name; // Match to package file extensions (e.g. *.zip) Match match = packageProvider.Pattern.Match(filename); // Don't replace if (!match.Success) { continue; } // Convert path to structured format PackageFileReference fileReference = new PackageFileReference(filename, match.Success, null, filename); // Create file entry PackageFileInfo newFileInfo = new PackageFileInfo(packageProvider, fileReference); newFileInfo.filename = filename; // Set new entry files[i] = newFileInfo; } return(files); }
public FileProcess(IOptions <ClientSettings> clientSettings, IFileProvider fileProvider) { _clientSettings = clientSettings; _fileProvider = fileProvider; _files = _fileProvider.GetDirectoryContents(_clientSettings.Value.FileDirectoryPath); _uploadedFiles = ExtractFiles(); }
public EncryptedDirectoryContents( KeyManagementServiceClient kms, IDirectoryContents innerDirectoryContents) { _kms = kms; _innerDirectoryContents = innerDirectoryContents; }
private IEnumerable <IFileInfo> FilterViewFiles(IDirectoryContents directory) { return(directory .Where(f => !f.IsDirectory && !Contains(f.Name, "_ViewStart") && !Contains(f.Name, "_ViewImports") && f.Name.EndsWith(FILE_EXTENSION, StringComparison.OrdinalIgnoreCase))); }
public async Task OnGetAsync() { DatabaseFiles = await _context.File.AsNoTracking().ToListAsync(); PhysicalFiles = _fileProvider.GetDirectoryContents(string.Empty); ModelFiles = _fileProvider.GetDirectoryContents("\\model\\"); DataFiles = _fileProvider.GetDirectoryContents("\\data\\"); }
public AppTextAdminInitializer(ILogger <AppTextAdminInitializer> logger, IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; var embeddedProvider = new EmbeddedFileProvider(typeof(AppTextAdminInitializer).Assembly); _translationsContents = embeddedProvider.GetDirectoryContents(""); _logger = logger; }
private bool GetTemplateDictionary( IDirectoryContents templateDirectory, out IDictionary <string, TemplateData> templates ) { bool correct = true; templates = new Dictionary <string, TemplateData>(StringComparer.InvariantCultureIgnoreCase); foreach (var subdir in templateDirectory.Where(c => c.IsDirectory)) { try { if (subdir.Name.Contains("_")) { logger.LogError("The name of the template directory '{SubdirectoryName}' contains a underscore.", subdir.Name); correct = false; } else { using var subDirFileProvider = new PhysicalFileProvider(subdir.PhysicalPath); foreach ( var file in subDirFileProvider.GetDirectoryContents("") .Where(f => !f.IsDirectory && f.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ) { try { var match = Regex.Match(file.Name, @"^(.*?_((?:-|\+)?(?:0|[0-9]\d*)))\.xml$", RegexOptions.IgnoreCase); if (match.Success) { var key = $"{subdir.Name}_{match.Groups[1].Value}"; using var fileStream = file.CreateReadStream(); templates[key] = GetTemplateData(key, match.Groups[2].Value, fileStream); } else { logger.LogError("The file name of {subDirName}\\{fileName} doesn't end with an unix timestamp", subdir.Name, file.Name); correct = false; } } catch (Exception e) { logger.LogError(e, "Error in template file {subDirName}\\{fileName}", subdir.Name, file.Name); correct = false; } } } } catch (Exception e) { logger.LogError(e, "Error in template directory {subDirName}\\.", subdir.Name); correct = false; } } return(correct); }
public HomeController( IHostingEnvironment env, INodeBuilderService <MiniJava.Program> astBuilder, INodeBuilderService <Assembly> ilBuilder) { _paths = env.WebRootFileProvider.GetDirectoryContents("sources"); _astBuilder = astBuilder; _ilBuilder = ilBuilder; }
public IActionResult Uploads() { IDirectoryContents contents = _fileProvider.GetDirectoryContents("wwwroot/uploads"); IOrderedEnumerable <IFileInfo> lastModified = contents.ToList() .OrderByDescending(f => f.LastModified); return(View(lastModified)); }
IFileInfo[] GetFiles() { IFileInfo[] files = null; string subdir = null; // Open as package PackageFileReference package_to_open = directoryReference.IsPackageFile ? directoryReference : directoryReference.Parent; using (var fp = packageProvider.TryOpenPackage(package_to_open)) { if (fp != null) { subdir = directoryReference.IsPackageFile ? "" : directoryReference.Name; files = fp.GetDirectoryContents(subdir).ToArray(); } } // Open as directory if (files == null) { using (var fp = packageProvider.TryOpenPackage(directoryReference.Parent)) { if (fp != null) { subdir = directoryReference.Name; IDirectoryContents dir = fp.GetDirectoryContents(subdir); files = fp.GetDirectoryContents(subdir).ToArray(); } } } // Convert package entries to package file infos if (files != null) { for (int i = 0; i < files.Length; i++) { // Get file reference string filename = files[i].Name; // Match to package file extensions (e.g. *.zip) Match match = packageProvider.Pattern.Match(filename); // don't replace //if (!match.Success) continue; // Convert path to structured format PackageFileReference fileReference = new PackageFileReference(subdir == "" || subdir == "/" ? filename : subdir + "/" + filename, match.Success, package_to_open, null); // Create file entry PackageFileInfo newFileInfo = new PackageFileInfo(packageProvider, fileReference); newFileInfo.filename = filename; // Set new entry files[i] = newFileInfo; } return(files); } return(no_files); }
public List <IModule> LoadModules(IDirectoryContents moduleRootFolder) { foreach (var moduleFolder in moduleRootFolder.Where(x => x.IsDirectory)) { try { var binFolder = new DirectoryInfo(Path.Combine(moduleFolder.PhysicalPath, "bin")); if (!binFolder.Exists) { continue; } foreach (var file in binFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories)) { Assembly assembly; try { assembly = NccAssemblyLoader.LoadFromFileName(file.FullName); } catch (FileLoadException ex) { continue; } catch (BadImageFormatException ex) { continue; } if (assembly.FullName.Contains(moduleFolder.Name)) { if (modules.Count(x => x.Folder == moduleFolder.Name && x.Path == moduleFolder.PhysicalPath) == 0) { modules.Add(new Module { Folder = moduleFolder.Name, Assembly = assembly, Path = moduleFolder.PhysicalPath }); } } else { DependencyContextLoader.Default.Load(assembly); } } LoadModuleDependencies(moduleFolder); } catch (Exception ex) { throw new Exception("Could not load module from " + moduleFolder); } } GlobalContext.SetModuleDependencies(_moduleDependencies); return(modules); }
public IEnumerable <IFileInfo> Get() { IDirectoryContents contents = FileProvider.GetDirectoryContents(FileService.FILES_DIRECTORY); var files = contents .OrderByDescending(f => f.LastModified) .ToList(); return(files); }
public void LoadModules(IDirectoryContents moduleRootFolder, ILogger logger) { _logger = logger; foreach (var moduleFolder in moduleRootFolder.Where(x => x.IsDirectory).ToList()) { try { var binFolder = new DirectoryInfo(Path.Combine(moduleFolder.PhysicalPath, "bin")); if (!binFolder.Exists) { continue; } foreach (var file in binFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories)) { Assembly assembly; try { assembly = NccAssemblyLoader.LoadFromFileName(file.FullName); } catch (FileLoadException ex) { _logger.LogWarning(ex.Message, ex); continue; } catch (BadImageFormatException ex) { _logger.LogWarning(ex.Message, ex); continue; } if (assembly.FullName.Contains(moduleFolder.Name)) { if (modules.Count(x => x.Folder == moduleFolder.Name && x.Path == moduleFolder.PhysicalPath) == 0) { modules.Add(new Module { ExecutionOrder = 100, ModuleName = moduleFolder.Name, Folder = moduleFolder.Name, Assembly = assembly, Path = moduleFolder.PhysicalPath }); } } else { DependencyContextLoader.Default.Load(assembly); } } } catch (Exception ex) { _logger.LogWarning("Could not load module from " + moduleFolder); _logger.LogError(ex.Message, ex); //throw new Exception("Could not load module from " + moduleFolder); } } }
public List <IFileInfo> GetAllFiles(string path) { IDirectoryContents contents = _fileProvider.GetDirectoryContents(Path.Combine("wwwroot", "uploads", path)); var lastModified = contents .OrderByDescending(f => f.LastModified) .ToList(); return(lastModified); }
public override void Run() { string root = AppDomain.CurrentDomain.BaseDirectory; Console.WriteLine($"Root:{root}"); IFileProvider fileProvider = new PhysicalFileProvider(root); IDirectoryContents contents = fileProvider.GetDirectoryContents("/"); Console.WriteLine(contents.AsFormatJsonStr()); }
private static IFileProvider MakeFileProvider(IDirectoryContents directoryContents = null) { if (directoryContents == null) { directoryContents = MakeDirectoryContents(); } var fileProvider = new Mock <IFileProvider>(); fileProvider.Setup(fp => fp.GetDirectoryContents(It.IsAny <string>())) .Returns(directoryContents); return(fileProvider.Object); }
public PhysicalDirectory(string physicalPath, IDirectoryContents directoryContents) { _physicalPath = physicalPath; _directoryContents = directoryContents; }
private static IFileProvider MakeFileProvider(IDirectoryContents directoryContents = null) { if (directoryContents == null) { directoryContents = MakeDirectoryContents(); } var fileProvider = new Mock<IFileProvider>(); fileProvider.Setup(fp => fp.GetDirectoryContents(It.IsAny<string>())) .Returns(directoryContents); return fileProvider.Object; }
private bool TryGetDirectoryInfo(PathString subpath, out IDirectoryContents contents) { contents = _options.FileProvider.GetDirectoryContents(subpath.Value); return contents.Exists; }