public Task <bool> PurgeAllAsync()
        {
            var hasErrors = false;
            var folders   = _fileProvider.GetDirectoryContents(String.Empty);

            foreach (var fileInfo in folders)
            {
                if (fileInfo.IsDirectory)
                {
                    // Sitemap cache only stores files, so any folder has been created by the user and will be ignored.
                    continue;
                }
                else
                {
                    try
                    {
                        File.Delete(fileInfo.PhysicalPath);
                    }
                    catch (IOException ex)
                    {
                        _logger.LogError(ex, "Error deleting cache file {Path}", fileInfo.PhysicalPath);
                        hasErrors = true;
                    }
                }
            }

            return(Task.FromResult(hasErrors));
        }
Beispiel #2
0
        public Task CleanSitemapCacheAsync(IEnumerable <string> validCacheFileNames)
        {
            var folders = _fileProvider.GetDirectoryContents(String.Empty);

            foreach (var fileInfo in folders)
            {
                if (fileInfo.IsDirectory)
                {
                    // Sitemap cache only stores files, so any folder that has been created by the user will be ignored.
                    continue;
                }
                else
                {
                    // Check if the file is valid and still needs to be cached.
                    if (validCacheFileNames.Contains(fileInfo.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    try
                    {
                        File.Delete(fileInfo.PhysicalPath);
                    }
                    catch (IOException ex)
                    {
                        _logger.LogError(ex, "Error deleting cache file {Path}", fileInfo.PhysicalPath);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var pluginDir = Path.Combine(AppContext.BaseDirectory, @"Plugins");

            if (!Directory.Exists(pluginDir))
            {
                Directory.CreateDirectory(pluginDir);
            }
            IFileProvider fileProvider = new PhysicalFileProvider(pluginDir);

            OldFiles.AddRange(fileProvider.GetDirectoryContents(""));
            ChangeToken.OnChange(() => fileProvider.Watch("*"), () =>
            {
                var fileInfos = fileProvider.GetDirectoryContents("");
                // 删除的文件
                var delFiles = OldFiles.Where(a => !fileInfos.Any(b => b.PhysicalPath == a.PhysicalPath));
                // 添加的文件
                var addFiles = fileInfos.Where(a => !OldFiles.Any(b => b.PhysicalPath == a.PhysicalPath));
                // 修改的文件 判断:新文件中有并且修改时间大于旧文件
                var modFiles = OldFiles.Where(a => fileInfos.FirstOrDefault(b => b.PhysicalPath == a.PhysicalPath)?.LastModified > a.LastModified);

                var allFiles = delFiles.ToDictionary(a => a.Name, status => 3)
                               .Union(addFiles.ToDictionary(a => a.Name, status => 1))
                               .Union(modFiles.ToDictionary(a => a.Name, status => 2));
                Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.FFFFFF")} {string.Join("\r\n", allFiles.Select(kv => $"{kv.Key} : {(kv.Value==1?"Add":(kv.Value==2?"Mod":"Del"))}"))}");

                // 最后文件列表刷新
                OldFiles.Clear();
                OldFiles.AddRange(fileInfos);
            });
            while (true)
            {
                Task.Delay(5 * 1000).Wait();
            }
        }
        public JsonResult FileNames()
        {
            List <FileStructure> filesFound = new List <FileStructure>();

            try
            {
                PhysicalFileProvider           rootProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory() + "/assets");
                IOrderedEnumerable <IFileInfo> rootContents = rootProvider.GetDirectoryContents(string.Empty).OrderBy(x => x.Name);
                foreach (var item in rootContents)
                {
                    string videoName   = null;
                    string folderFound = null;
                    string imageFound  = null;
                    int    indexCount  = 0;
                    List <VideosInFolder> folderChildren = null;
                    if (item.Name.EndsWith(".mp4"))
                    {
                        videoName  = item.Name;
                        imageFound = item.Name.Replace(".mp4", ".jpg");
                        filesFound.Add(new FileStructure
                        {
                            video    = videoName,
                            folder   = folderFound,
                            image    = imageFound,
                            index    = indexCount,
                            children = folderChildren
                        });
                    }
                    else if (item.IsDirectory)
                    {
                        folderFound = item.Name;
                        imageFound  = item.Name + ".jpg";
                        IOrderedEnumerable <IFileInfo> contents = rootProvider.GetDirectoryContents(item.Name).OrderBy(x => x.Name);
                        folderChildren = new List <VideosInFolder>();
                        foreach (var videoFile in contents)
                        {
                            folderChildren.Add(new VideosInFolder()
                            {
                                video = videoFile.Name
                            });
                        }
                        filesFound.Add(new FileStructure
                        {
                            video    = videoName,
                            folder   = folderFound,
                            image    = imageFound,
                            index    = indexCount,
                            children = folderChildren
                        });
                    }
                    indexCount++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(Json(filesFound));
        }
Beispiel #5
0
 /// <summary>
 /// Returns the contents of the given directory
 /// </summary>
 /// <param name="subpath">Target path</param>
 /// <returns>Directory contents</returns>
 public IDirectoryContents GetDirectoryContents(string subpath)
 {
     lock (this)
     {
         return(_provider.GetDirectoryContents(subpath));
     }
 }
Beispiel #6
0
        public DataAccessLayer()
        {
            var provider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            var filePath = Path.Combine("wwwroot", "contents", "loginstate.json");

            StateManagementFile = provider.GetFileInfo(filePath);
            var _fileFilter = Path.Combine("wwwroot", "contents", "Assets");
            var svgFiles    = provider.GetDirectoryContents(_fileFilter);

            if (BrandSVGFiles == null)
            {
                BrandSVGFiles = new List <IFileInfo>();
            }
            foreach (var i in svgFiles)
            {
                if (!i.IsDirectory && i.Name.EndsWith(".svg"))
                {
                    BrandSVGFiles.Add(i);
                }
            }
            #region change tracking
            //var contents = provider.GetDirectoryContents(string.Empty);
            //var _fileFilter = Path.Combine("TextFiles", "*.txt");
            //IChangeToken token = provider.Watch(_fileFilter);
            //var tcs = new TaskCompletionSource<object>();
            //token.RegisterChangeCallback(state =>((TaskCompletionSource<object>)state).TrySetResult(null), tcs);
            //await tcs.Task.ConfigureAwait(false);
            #endregion
        }
Beispiel #7
0
        public void Export(string subpath)
        {
            var contents = FileProvider.GetDirectoryContents(subpath);

            if (contents.Exists == true)
            {
                foreach (var file in contents)
                {
                    if (file.IsDirectory)
                    {
                        //排除存在的目录
                        if (options.Excludes.Contains(file.PhysicalPath))
                        {
                            options.Excludes.Remove(file.PhysicalPath);
                            continue;
                        }
                        this.Export(Path.GetRelativePath(FileProvider.Root, file.PhysicalPath));
                    }
                    else
                    {
                        this.ExportFile(file.PhysicalPath);
                    }
                }
            }
            else
            {
                if (FileProvider.GetFileInfo(subpath).Exists == true)
                {
                    this.ExportFile(subpath);
                }
            }
        }
        private byte[] GetCompanyLogo()
        {
            var path = Path.Combine(_env.ContentRootPath, "AppData/Companies", _unit.Info.CompanyId.ToString());

            if (!Directory.Exists(path))
            {
                return(null);
            }

            IFileProvider provider     = new PhysicalFileProvider(path);
            IFileInfo     logoFileInfo = provider.GetDirectoryContents("").Where(x => x.Name.StartsWith("logo.")).FirstOrDefault();

            using (var companyLogoStream = new MemoryStream())
                using (var readStream = logoFileInfo.CreateReadStream())
                {
                    if (logoFileInfo == null)
                    {
                        return(null);
                    }

                    readStream.CopyTo(companyLogoStream);

                    return(companyLogoStream.ToArray());
                }
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            var provider    = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            var commonmarks = provider.GetDirectoryContents(@"commonmarks");

            app.UseStaticFiles();

            app.Run(async(context) =>
            {
                var pathElements = context.Request.Path.Value.Split('/');
                if (pathElements.Length != 2)
                {
                    return;
                }

                var requestName = pathElements[1];
                if (string.IsNullOrEmpty(requestName))
                {
                    requestName = "index";
                }

                if (commonmarks.Exists && commonmarks.Any(x => x.Name.Split('.')?[0] == requestName))
                {
                    var filePath = $"{provider.Root}commonmarks\\{requestName}.md";
                    using (var stream = File.OpenRead(filePath))
                        using (var reader = new StreamReader(stream))
                        {
                            var content  = await reader.ReadToEndAsync();
                            var htmlPart = CommonMarkConverter.Convert(content);
                            await context.Response.WriteAsync(string.Format(HtmlTemplate, requestName, htmlPart));
                        }
                }
            });
        }
        // 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);
        }
        public object GetContentForPath(HttpContext context)
        {
            var pipeline = new MarkdownPipelineBuilder()
                           .UseAdvancedExtensions()
                           .Build();

            var request = context.Request.Path.Value.Trim(new[] { '/' });

            if (string.IsNullOrWhiteSpace(request))
            {
                request = "index.md";
            }

            PhysicalFileProvider pfp = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            var dirContents          = pfp.GetDirectoryContents(BasePath);

            StringBuilder sb = new StringBuilder();

            foreach (var file in dirContents)
            {
                if (ValidExtensions.Any(ext => file.Name.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)))
                {
                    if (request == file.Name)
                    {
                        var fileContents = Markdown.ToHtml(File.ReadAllText(file.PhysicalPath), pipeline);

                        sb.AppendLine(fileContents);
                    }
                }
            }

            return(sb.ToString());
        }
Beispiel #12
0
 /// <summary>
 /// Listen for changes in subfolders
 /// </summary>
 /// <param name="rootPath">Watching Root Path</param>
 /// <param name="onChange">Callback when change</param>
 private void SubfolderChangeWatch(string rootPath, Action <IEnumerable <string> > onChange)
 {
     FileProvider = new PhysicalFileProvider(rootPath);
     // 递归查询所有子文件
     Files.AddRange(FileProvider.GetDirectoryDepthContents("").Where(f => !f.IsDirectory));
     // 监听监听所有文件,当文件发生修改时反应为某个子文件夹的修改,在最后将修改的文件夹路径打印出来
     ChangeToken.OnChange(() => FileProvider.Watch("*"), () =>  // filter Example: **/*.cs, *.*, subFolder/**/*.cshtml.
     {
         // 查询所有子文件
         var files = FileProvider.GetDirectoryDepthContents("").Where(f => !f.IsDirectory);
         // 查询变化的文件
         var modFiles = Files.Where(a => (!files.Any(b => b.PhysicalPath == a.PhysicalPath)) ||
                                    files.FirstOrDefault(b => b.PhysicalPath == a.PhysicalPath)?.LastModified > a.LastModified)
                        .Union(files.Where(a => !Files.Any(b => b.PhysicalPath == a.PhysicalPath)))
                        .Select(f => f.PhysicalPath);
         // 查询根目录下的子文件夹
         var subfolders = FileProvider.GetDirectoryContents("");
         // 查询发生变化的文件夹
         var modDirs = subfolders.Select(f => f.PhysicalPath).Where(a => modFiles.Any(b => b.Contains(a)));
         // 有文件夹修改则回调
         if (modDirs.Any())
         {
             onChange(modDirs);
         }
         // 刷新暂存文件列表
         Files.Refresh(files);
     });
 }
Beispiel #13
0
        static void Main(string[] args)
        {
            var phyProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            var contents    = phyProvider.GetDirectoryContents("/");

            foreach (var item in contents)
            {
                Console.WriteLine(item.Name);
            }

            var embProvider = new EmbeddedFileProvider(typeof(Program).Assembly);
            var html        = embProvider.GetFileInfo("emb.html");

            Console.WriteLine($"获取到嵌入式文件:{html.Exists}");

            Console.WriteLine("=====↓CompositeFileProvider↓=====");

            var compositeProvider = new CompositeFileProvider(phyProvider, embProvider);
            var comContent        = compositeProvider.GetDirectoryContents("/");

            foreach (var item in comContent)
            {
                Console.WriteLine(item.Name);
            }

            Console.WriteLine("=====END=====");
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            IFileProvider fileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            var           contents     = fileProvider.GetDirectoryContents("/");

            foreach (var item in contents)
            {
                Console.WriteLine(item.Name);
                //Stream stream=item.CreateReadStream();
            }
            Console.WriteLine("===================");

            //这种方式可正常包含嵌入资源
            //IFileProvider fileProvider1 = new EmbeddedFileProvider(typeof(Program).Assembly, "_18_FileProviderDemo");

            //在csproj中不能指定rootNamespces,才能正常包含嵌入资源
            IFileProvider fileProvider1 = new EmbeddedFileProvider(typeof(Program).Assembly);

            var html = fileProvider1.GetFileInfo("a.html");

            Console.WriteLine(html);
            Console.WriteLine("======================");

            IFileProvider fileProvider2 = new CompositeFileProvider(fileProvider, fileProvider1);

            var contents1 = fileProvider2.GetDirectoryContents("/");

            foreach (var item in contents1)
            {
                Console.WriteLine(item.Name);
            }
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            //文件提供程序
            IFileProvider physicalFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            var           contents             = physicalFileProvider.GetDirectoryContents("/");

            foreach (var item in contents)
            {
                Console.WriteLine(item.Name);
            }
            //嵌入式文件提供程序
            IFileProvider embeddedFileProvider = new EmbeddedFileProvider(typeof(Program).Assembly);
            var           embeddedFile         = embeddedFileProvider.GetFileInfo("Embedded.txt");

            Console.WriteLine(embeddedFile.Length);
            //组合文件提供程序
            IFileProvider compositeFileProvider = new CompositeFileProvider(physicalFileProvider, embeddedFileProvider);
            var           compositeFile         = compositeFileProvider.GetDirectoryContents("/");

            foreach (var item in compositeFile)
            {
                Console.WriteLine(item.Name);
            }
            Console.ReadLine();
        }
Beispiel #16
0
        private static FilePath GetChild(PhysicalFileProvider provider,
                                         IFileInfo fileInfo, string parentDirectoryName)
        {
            var path    = $"{parentDirectoryName}{fileInfo.Name}/";
            var newPath = new FilePath
            {
                Name       = fileInfo.Name,
                ParentPath = parentDirectoryName,
            };

            if (fileInfo.IsDirectory)
            {
                newPath.Directory = true;
                newPath.FileType  = FileType.Directory;
                newPath.Children  = new List <FilePath>();
                foreach (var content in provider.GetDirectoryContents(path))
                {
                    newPath.Children.Add(GetChild(provider, content, path));
                }
            }
            else
            {
                newPath.FileType = GetFileType(fileInfo);
            }
            return(newPath);
        }
Beispiel #17
0
        public IActionResult Index()
        {
            ViewBag.Environment = _environment.EnvironmentName;

            var provider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            var contents = provider.GetDirectoryContents(string.Empty);
            var fileInfo = provider.GetFileInfo("wwwroot/js/site.js");
            var path     = Path.Combine("advisor", "caco");
            var advFiles = _fileProvider.GetDirectoryContents(path);

            var test = Directory.GetCurrentDirectory();

            ViewBag.Contents  = advFiles;
            ViewBag.Directory = Directory.GetCurrentDirectory();
            //PRUEBAS

            var          obj1 = new ClaseMaestra();
            var          obj2 = new ClaseDerivada();
            ClaseMaestra obj3 = new ClaseDerivada();

            var test1 = obj1.Metodo();
            var test2 = obj1.MetodoVirtual();

            var test3 = obj2.Metodo();
            var test4 = obj2.MetodoVirtual();
            var test5 = obj2.MetodoBase();
            var test6 = obj2.MetodoVirtualBase();

            var test7 = obj3.Metodo();
            var test8 = obj3.MetodoVirtual();

            return(View());
        }
        public Task ImportExistingAsync(string importPath, CancellationToken stoppingToken)
        {
            _logger.LogInformation("Importing {type} Files from {Path}", typeof(T).Name, importPath);

            var fileProvider = new PhysicalFileProvider(importPath);

            var files      = fileProvider.GetDirectoryContents("./").Where(IsImportFile).ToArray();
            var serializer = JsonSerializer.Create();

            var count = 0;

            foreach (var file in files)
            {
                if (stoppingToken.IsCancellationRequested)
                {
                    _logger.LogWarning("Importing of {type}s stopped because of stopping application", typeof(T).Name);
                    break;
                }

                using (var streamReader = new StreamReader(file.CreateReadStream()))
                {
                    var jsonReader     = new JsonTextReader(streamReader);
                    var existingOrders = serializer.Deserialize <T[]>(jsonReader);
                    count += existingOrders.Length;
                    UpdateItems(existingOrders);
                }
            }

            _storage.ResetModifiedDates();

            _logger.LogInformation("Imported up to {count} {type}s", count, typeof(T).Name);

            return(Task.CompletedTask);
        }
Beispiel #19
0
        /// <inheritdoc/>
        public async Task <Dictionary <string, DateTime> > GetUpdatedFilesList(string userId, DateTime lastModifiedDate, bool mbTiles)
        {
            _logger.LogInformation($"Getting the list of offline files for user: {userId}, mbtiles: {mbTiles}");
            var filesDictionary = new Dictionary <string, DateTime>();

            if (!await _receiptValidationGateway.IsEntitled(userId))
            {
                return(new Dictionary <string, DateTime>());
            }
            var contents = _fileProvider.GetDirectoryContents(string.Empty);

            foreach (var content in contents)
            {
                if (_fileSystemHelper.IsHidden(content.PhysicalPath))
                {
                    continue;
                }
                if (lastModifiedDate != DateTime.MinValue && content.LastModified.DateTime - lastModifiedDate <= new TimeSpan(0, 0, 1))
                {
                    continue;
                }
                // HM TODO: 03.2020 - remove this when all requests are sending mbtiles true
                if ((mbTiles && (content.Name.EndsWith(".mbtiles") || content.Name.StartsWith("style"))) ||
                    !mbTiles && content.Name.EndsWith(".ihm"))
                {
                    filesDictionary[content.Name] = content.LastModified.DateTime;
                }
            }
            return(filesDictionary);
        }
Beispiel #20
0
        /*
         * 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);
            }
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            // 物理文件
            IFileProvider provider1 = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            var           contents  = provider1.GetDirectoryContents("/");
            //foreach (var item in contents)
            //{
            //    // 读取文件流
            //    //var fileStream = item.CreateReadStream();
            //    Console.WriteLine(item.Name);
            //}

            // 嵌入文件
            IFileProvider provider2 = new EmbeddedFileProvider(typeof(Program).Assembly);
            var           html      = provider2.GetFileInfo("emb.html");
            //var htmlStream = html.CreateReadStream();
            //var buffer = new byte[htmlStream.Length];
            //htmlStream.ReadAsync(buffer, 0, buffer.Length);
            //Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));

            // 组合文件
            IFileProvider provider3 = new CompositeFileProvider(provider1, provider2);

            var contents3 = provider3.GetDirectoryContents("/");

            foreach (var item in contents3)
            {
                // 读取文件流
                //var fileStream = item.CreateReadStream();
                Console.WriteLine(item.Name);
            }

            Console.ReadLine();
        }
        private bool TryGetDirectoryInfo(ILibrary library, PathString subpath, out IDirectoryContents contents)
        {
            var fileProvider = new PhysicalFileProvider(library.Path);

            contents = fileProvider.GetDirectoryContents(subpath.Value);
            return(contents.Exists);
        }
Beispiel #23
0
        public void Test1()
        {
            //Microsoft.Extensions.FileProviders.Composite.CompositeDirectoryContents
            //    Microsoft.Extensions.FileProviders.NotFoundDirectoryContents
            //Microsoft.Extensions.FileProviders.Internal.PhysicalDirectoryContents
            //Microsoft.Extensions.FileProviders.PhysicalFileProvider
            var sss1 = new EmbeddedFileProvider(typeof(UnitTest1).Assembly);
            //var sss2 = new ManifestEmbeddedFileProvider(typeof(UnitTest1).Assembly);
            var sss3 = new PhysicalFileProvider(@"D:\Users\mccj\Source\Repos\FileManager\FileManager\");
            var sss4 = new NullFileProvider();
            var sss5 = new FileStorage.StoreFileProvider(new FileStorage.Standard.PhysicalFileSystemStore(@"D:\Users\mccj\Source\Repos\FileManager\FileManager\"));
            var sss6 = new FileStorage.StoreFileProvider(new FileStorage.Standard.FileSystemStore(@"D:\Users\mccj\Source\Repos\FileManager\FileManager\"));
            var sss7 = new CompositeFileProvider(sss1, sss3, sss4, sss5, sss6);

            var sdfsd = sss4.Watch("");
            var rr    = sss4.GetFileInfo("");

            var sss11  = sss3.GetFileInfo("aaaa");
            var sssd11 = sss5.GetFileInfo("aaaa");
            var sssc11 = sss6.GetFileInfo("aaaa");

            var sss113  = sss3.GetFileInfo("FileProviderStore");
            var sssd113 = sss5.GetFileInfo("FileProviderStore");
            var sssd213 = sss6.GetFileInfo("FileProviderStore");

            var sss112  = sss3.GetFileInfo("ApplicationBuilderExtensions.cs");
            var sssd112 = sss5.GetFileInfo("ApplicationBuilderExtensions.cs");
            var sssc112 = sss6.GetFileInfo("ApplicationBuilderExtensions.cs");


            var sss  = sss3.GetDirectoryContents("");
            var sssd = sss5.GetDirectoryContents("");
            var sssc = sss6.GetDirectoryContents("");

            var sss75 = sss3.GetDirectoryContents("aaaaa");
            var sssd5 = sss5.GetDirectoryContents("aaaaa");
            var sssdc = sss6.GetDirectoryContents("aaaaa");

            var sss76  = sss3.GetDirectoryContents("FileProviderStore");
            var sssd6  = sss5.GetDirectoryContents("FileProviderStore");
            var sssdcc = sss6.GetDirectoryContents("FileProviderStore");


            var sdsdasd = sss7.GetDirectoryContents("");
            //sss6.GetDirectoryContents("");
            //sss6.GetFileInfo("");
        }
        public IActionResult GetImages()
        {
            var provider = new PhysicalFileProvider(_env.WebRootPath);
            var files    = provider.GetDirectoryContents("images");
            var fnames   = files.Select(x => x.Name);

            return(Ok(fnames));
        }
Beispiel #25
0
        //public byte[] GetFileFromServer(string fileName)
        //{
        //    //var data = net.DownloadData(@"C:\Users\ArvīdsKramiņš\Desktop\Backend\FileUploadStorage\file");
        //    var fileBytes = System.IO.File.ReadAllBytes(@"C:\Users\ArvīdsKramiņš\Desktop\Backend\FileUploadStorage\file.ts");
        //    return fileBytes;
        //}

        public IDirectoryContents getAllPhysicalFiles()
        {
            var pathToFiles = @"C:\Users\Arvids\Desktop\ShopFileStorage";
            var provider    = new PhysicalFileProvider(pathToFiles);
            var fileInfo    = provider.GetDirectoryContents(@"\");

            return(fileInfo);
        }
Beispiel #26
0
        /// <summary>
        /// cshtml
        /// </summary>
        /// <param name="path"></param>
        /// <param name="endwith"></param>
        /// <returns></returns>
        public Task <List <Dir> > GetPathExsitCshtml(string path, string endwith)
        {
            var provider = new PhysicalFileProvider(path);
            var ppath    = provider.GetDirectoryContents(string.Empty).ToList()
                           .Where(x => x.IsDirectory || x.Name.EndsWith($".{endwith}"))
                           .Select(x => new Dir(x.PhysicalPath, path)).ToList();

            return(Task.FromResult(ppath));
        }
Beispiel #27
0
        public IActionResult OnGetImageList()
        {
            var provider = new PhysicalFileProvider(webHostEnvironment.WebRootPath);
            var contents = provider.GetDirectoryContents(Path.Combine("mediaUpload", "article"));
            var X        = contents.OrderBy(m => m.Name);

            //  var fileList = "";// contents.f
            return(new JsonResult(X));
        }
Beispiel #28
0
        /// <summary>
        /// 获取路径下所有文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Task <List <Dir> > GetPathExsitDir(string path)
        {
            var provider = new PhysicalFileProvider(path);
            var ppath    = provider.GetDirectoryContents(string.Empty).ToList()
                           .Where(x => x.IsDirectory)
                           .Select(x => new Dir(x.PhysicalPath, path)).ToList();

            return(Task.FromResult(ppath));
        }
        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 static IFileInfo[] GetMigrationScripts()
        {
            var folder = Directory.GetCurrentDirectory() + @"/../../../../ReadMoreAPI/Migrations/";

            folder = Path.GetFullPath(folder);
            var fileProvider = new PhysicalFileProvider(folder);

            return(fileProvider.GetDirectoryContents("").ToArray());
        }