public BaseDocumentHandler(IFileProvider fileProvider, string subpath)
 {
     FileInfo = AcceptedExtensions
         .Select(x => fileProvider.GetFileInfo(subpath + x))
         .Where(x => x.Exists)
         .FirstOrDefault();
 }
Example #2
0
 public static IFileInfo DepartureSearch() => fileProvider.GetFileInfo($"{nameof(DepartureSearch)}.xml");
 public static IEnumerable<NavigationWidget> SuiteWidgets(IFileProvider fileProvider)
 {
     var file = fileProvider.GetFileInfo("/shared/nav-beta.json");
     var navigationJson = IOFile.ReadAllText(file.PhysicalPath);
     return JsonConvert.DeserializeObject<IEnumerable<NavigationWidget>>(navigationJson);
 }
        //读取目录下所有文件内容
        private void ResolveFileInfo(StringBuilder output, string path, string suffix)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            Encoding encoding = Encoding.GetEncoding("gb2312");

            output.AppendLine("UserID    Golds    RecordDate");

            IDirectoryContents dir = _fileProvider.GetDirectoryContents(path);

            foreach (IFileInfo item in dir)
            {
                if (item.IsDirectory)
                {
                    ResolveFileInfo(output,
                                    item.PhysicalPath.Substring(Directory.GetCurrentDirectory().Length),
                                    suffix);
                }
                else
                {
                    if (item.Name.Contains(suffix))
                    {
                        var userList = new List <UserGolds>();
                        var user     = new UserGolds();

                        IFileInfo file = _fileProvider.GetFileInfo(path + "\\" + item.Name);

                        using (var stream = file.CreateReadStream())
                        {
                            using (var reader = new StreamReader(stream, encoding))
                            {
                                string content = reader.ReadLine();

                                while (content != null)
                                {
                                    if (content.Contains("begin"))
                                    {
                                        user = new UserGolds();
                                    }
                                    if (content.Contains("写入时间"))
                                    {
                                        DateTime recordDate;
                                        string   strRecordDate = content.Substring(content.IndexOf(":") + 1).Trim();
                                        if (DateTime.TryParse(strRecordDate, out recordDate))
                                        {
                                            user.RecordDate = recordDate;
                                        }
                                    }

                                    if (content.Contains("userid"))
                                    {
                                        int    userID;
                                        string strUserID = content.Substring(content.LastIndexOf("=") + 1).Trim();
                                        if (int.TryParse(strUserID, out userID))
                                        {
                                            user.UserID = userID;
                                        }
                                    }

                                    if (content.Contains("golds"))
                                    {
                                        int    golds;
                                        string strGolds = content.Substring(content.LastIndexOf("=") + 1).Trim();
                                        if (int.TryParse(strGolds, out golds))
                                        {
                                            user.Golds = golds;
                                        }
                                    }

                                    if (content.Contains("end"))
                                    {
                                        var userMax = userList.FirstOrDefault(u => u.UserID == user.UserID);
                                        if (userMax == null || userMax.UserID <= 0)
                                        {
                                            userList.Add(user);
                                        }
                                        else if (userMax.RecordDate < user.RecordDate)
                                        {
                                            userList.Remove(userMax);
                                            userList.Add(user);
                                        }
                                    }

                                    content = reader.ReadLine();
                                }
                            }
                        }

                        if (userList != null && userList.Count > 0)
                        {
                            foreach (var golds in userList.OrderBy(u => u.RecordDate))
                            {
                                output.AppendLine(golds.UserID.ToString() + "    " + golds.Golds + "    " + golds.RecordDate);
                            }

                            output.AppendLine("");
                        }
                    }
                }
            }
        }
 public IFileInfo GetFileInfo(string subpath)
 {
     return(_fileProvider.GetFileInfo(subpath));
 }
 public override DirectoryInfoBase GetDirectory(string path)
 {
     return(new FileProviderGlobbingDirectory(_fileProvider, _fileProvider.GetFileInfo(path), this));
 }
Example #7
0
        private Task <CompilerCacheResult> CreateCacheEntry(
            string normalizedPath,
            Func <RelativeFileInfo, CompilationResult> compile)
        {
            TaskCompletionSource <CompilerCacheResult> compilationTaskSource = null;
            MemoryCacheEntryOptions cacheEntryOptions = null;
            IFileInfo fileInfo = null;
            Task <CompilerCacheResult> cacheEntry;

            // Safe races cannot be allowed when compiling Razor pages. To ensure only one compilation request succeeds
            // per file, we'll lock the creation of a cache entry. Creating the cache entry should be very quick. The
            // actual work for compiling files happens outside the critical section.
            lock (_cacheLock)
            {
                if (_cache.TryGetValue(normalizedPath, out cacheEntry))
                {
                    return(cacheEntry);
                }

                fileInfo = _fileProvider.GetFileInfo(normalizedPath);
                if (!fileInfo.Exists)
                {
                    var expirationToken = _fileProvider.Watch(normalizedPath);
                    cacheEntry = Task.FromResult(new CompilerCacheResult(new[] { expirationToken }));

                    cacheEntryOptions = new MemoryCacheEntryOptions();
                    cacheEntryOptions.AddExpirationToken(expirationToken);
                }
                else
                {
                    cacheEntryOptions = GetMemoryCacheEntryOptions(normalizedPath);

                    // A file exists and needs to be compiled.
                    compilationTaskSource = new TaskCompletionSource <CompilerCacheResult>();
                    cacheEntry            = compilationTaskSource.Task;
                }

                cacheEntry = _cache.Set <Task <CompilerCacheResult> >(normalizedPath, cacheEntry, cacheEntryOptions);
            }

            if (compilationTaskSource != null)
            {
                // Indicates that the file was found and needs to be compiled.
                Debug.Assert(fileInfo != null && fileInfo.Exists);
                Debug.Assert(cacheEntryOptions != null);
                var relativeFileInfo = new RelativeFileInfo(fileInfo, normalizedPath);

                try
                {
                    var compilationResult = compile(relativeFileInfo);
                    compilationResult.EnsureSuccessful();
                    compilationTaskSource.SetResult(
                        new CompilerCacheResult(compilationResult, cacheEntryOptions.ExpirationTokens));
                }
                catch (Exception ex)
                {
                    compilationTaskSource.SetException(ex);
                }
            }

            return(cacheEntry);
        }
        private string MatchFileCore(string path)
        {
            using (this._logger.BeginScope("Look-up for path: " + path))
            {
                bool slashPrefix = path[0].Equals('/');
                if (slashPrefix)
                {
                    path = path.Substring(1);
                }

                IFileProvider fileProvider = this._hostingEnvironment.WebRootFileProvider;

                // If we match straight away, don't bother
                IFileInfo straightMatch = fileProvider.GetFileInfo(path);
                if (straightMatch.Exists)
                {
                    this._logger.LogDebug($"Straight match via file path {straightMatch.PhysicalPath}");
                    return(path);
                }

                // Directory, attempt search in directory
                string file = Path.GetFileName(path);

                // Remove the ultimate extension to get the parts. The last part can be the file hash.
                file = file.Substring(0, file.Length - Extension.Length);

                string[] parts = file.Split('.');
                if (parts.Length > 1)
                {
                    file = string.Join('.', parts, 0, parts.Length - 1);
                }

                string pattern = file + ".*" + Extension;

                string webDirectoryPath = Path.GetDirectoryName(path);

                this._logger.LogDebug($"Matching files in {webDirectoryPath} according to pattern [{pattern}]");

                // Enumerate and find the latest written file
                DateTimeOffset lastWriteTime = DateTimeOffset.MinValue;
                IFileInfo      newestFile    = null;

                foreach (IFileInfo currentFile in fileProvider.GetDirectoryContents(webDirectoryPath))
                {
                    Debug.Assert(currentFile.Exists);

                    bool isMatch = currentFile.Name.StartsWith(file + ".", StringComparison.OrdinalIgnoreCase) &&
                                   currentFile.Name.EndsWith(Extension, StringComparison.OrdinalIgnoreCase);
                    if (!isMatch)
                    {
                        continue;
                    }

                    DateTimeOffset currentFileWriteTime = currentFile.LastModified;

                    if (currentFileWriteTime > lastWriteTime)
                    {
                        lastWriteTime = currentFileWriteTime;
                        newestFile    = currentFile;
                    }
                }

                if (newestFile == null)
                {
                    this._logger.LogInformation($"No matching files in {webDirectoryPath} according to pattern [{pattern}]");
                    return(null);
                }

                // Create new path
                string newPath = webDirectoryPath + "/" + newestFile.Name;

                this._logger.LogInformation($"Returning path {newPath} from {newestFile}");

                // Create watcher for directory
                if (this._hostingEnvironment.IsDevelopment())
                {
                    this._fileWatcherCache.GetOrAdd(webDirectoryPath, this.InitFileWatcher);
                }

                return(newPath);
            }
        }
Example #9
0
 public FileResult Get([FromQuery] string filename, [FromServices] IFileProvider fileProvider)
 {
     Console.WriteLine($"Sending file {filename}");
     return(File(fileProvider.GetFileInfo(filename).CreateReadStream(), System.Net.Mime.MediaTypeNames.Application.Octet));
 }
 public IActionResult Index()
 {
     DateTimeOffset lastModifiedDate = _fileProvider.GetFileInfo(@"Views\Home\Index.cshtml").LastModified;
     // use it wisely...
     return View();
 }
Example #11
0
        public IFileInfo GetFileInfo(string subpath)
        {
            var path = Path.Combine(_partialsFolder, subpath);

            return(_fileProvider.GetFileInfo(path));
        }
Example #12
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (!Inline)
            {
                return;
            }

            var src = output.Attributes["src"];

            if (src == null)
            {
                return;
            }

            var path = default(string);

            switch (src.Value)
            {
            case string p:
                path = p;
                break;

            case HtmlString s when s.Value != null:
                path = s.Value;
                break;

            case IHtmlContent pathHtmlContent:
                using (var tw = new StringWriter())
                {
                    pathHtmlContent.WriteTo(tw, NullHtmlEncoder.Default);
                    path = tw.ToString();
                }
                break;

            default:
                path = src?.Value?.ToString();
                break;
            }
            var resolvedPath = path ?? src.Value.ToString();

            var queryStringStartIndex = resolvedPath.IndexOf('?');

            if (queryStringStartIndex != -1)
            {
                resolvedPath = resolvedPath.Substring(0, queryStringStartIndex);
            }

            if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out Uri uri))
            {
                // Don't inline if the path is absolute
                return;
            }

            var fileInfo        = _wwwroot.GetFileInfo(resolvedPath);
            var requestPathBase = ViewContext.HttpContext.Request.PathBase;

            if (!fileInfo.Exists)
            {
                if (requestPathBase.HasValue &&
                    resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase))
                {
                    resolvedPath = resolvedPath.Substring(requestPathBase.Value.Length);
                    fileInfo     = _wwwroot.GetFileInfo(resolvedPath);
                }

                if (!fileInfo.Exists)
                {
                    // Don't inline if the file is not on the current server
                    return;
                }
            }

            using (var readStream = fileInfo.CreateReadStream())
                using (var reader = new StreamReader(readStream, Encoding.UTF8))
                {
                    output.Content.AppendHtml(reader.ReadToEnd());
                }

            output.Attributes.Remove(src);
        }
 private static void Configurator_ConfigureDataConnection(object sender, ConfigureDataConnectionWebEventArgs e)
 {
     if (e.ConnectionName == "excelDataConnection")
     {
         ExcelDataSourceConnectionParameters excelParams = new ExcelDataSourceConnectionParameters(fileProvider.GetFileInfo("Data/Sales.xlsx").PhysicalPath);
         e.ConnectionParameters = excelParams;
     }
 }
Example #14
0
 public async void LoadFileAsync(IFileProvider fileProvider)
 {
     fileProvider.GetDirectoryContents("").FirstOrDefault();
     var   task = Task.Run(() => Generate(fileProvider.GetFileInfo("").PhysicalPath));
     await task;
 }
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var path = (values[routeKey]).ToString();

            return(_files.GetFileInfo(path)?.Exists == true);
        }
Example #16
0
        private static bool TryFindFile(
            string directory,
            string fileName,
            string extension,
            IHostingEnvironment env,
            ICultureExpression requestedCulture,
            out IFileCultureInfo result)
        {
            string             filePath;
            string             targetName;
            string             culture;
            IFileInfo          file;
            IDirectoryContents contents;
            IFileProvider      provider = env.ContentRootFileProvider;

            if (requestedCulture.IsAllRegion)
            {
                // find by name
                // View.en.cshtml
                culture    = requestedCulture.Language;
                targetName = $"{fileName}.{culture}.{extension}";
                filePath   = $"{directory}/{targetName}";
                file       = provider.GetFileInfo(filePath);
                if (file.Exists && !file.IsDirectory)
                {
                    result = new FileCultureInfo(filePath, targetName, fileName, extension, requestedCulture);
                    return(true);
                }

                // try find directory named with language
                // en/View.cshtml
                contents = provider.GetDirectoryContents(directory);
                IFileInfo dir = contents.FirstOrDefault(x => x.IsDirectory && x.Name.Equals(culture));
                if (dir != null)
                {
                    targetName = $"{fileName}.{extension}";
                    filePath   = $"{directory}/{dir.Name}/{targetName}";
                    file       = provider.GetFileInfo(filePath);
                    if (file.Exists && !file.IsDirectory)
                    {
                        result = new FileCultureInfo(filePath, targetName, fileName, extension, requestedCulture);
                        return(true);
                    }
                }

                // find the first region having the same language
                // View.en-XX.cshtml
                string startsWithFilter = $"{fileName}.{culture}-";
                string endsWithFilter   = $".{extension}";
                file = contents.FirstOrDefault(x => !x.IsDirectory && x.Name.StartsWith(startsWithFilter) && x.Name.EndsWith(endsWithFilter));
                if (file != null)
                {
                    culture  = file.Name.Substring(fileName.Length + 1);
                    culture  = Path.GetFileNameWithoutExtension(culture);
                    filePath = $"{directory}/{file.Name}";
                    result   = new FileCultureInfo(filePath, file.Name, fileName, extension, culture.ParseCultureExpression());
                    return(true);
                }

                // try find directory named with the first region having the same language
                // en-XX/View.cshtml
                startsWithFilter = $"{culture}-";
                dir = contents.FirstOrDefault(x => x.IsDirectory && x.Name.StartsWith(startsWithFilter));
                if (dir != null)
                {
                    targetName = $"{fileName}.{extension}";
                    filePath   = $"{directory}/{dir.Name}/{targetName}";
                    file       = provider.GetFileInfo(filePath);
                    if (file.Exists && !file.IsDirectory)
                    {
                        culture = dir.Name;
                        result  = new FileCultureInfo(filePath, targetName, fileName, extension, culture.ParseCultureExpression());
                        return(true);
                    }
                }
            }
            else
            {
                // find by name
                // View.en-US.cshtml
                culture    = requestedCulture.DisplayName;
                targetName = $"{fileName}.{culture}.{extension}";
                filePath   = $"{directory}/{targetName}";
                file       = provider.GetFileInfo(filePath);
                if (file.Exists && !file.IsDirectory)
                {
                    result = new FileCultureInfo(filePath, targetName, fileName, extension, requestedCulture);
                    return(true);
                }

                // try find directory named with name
                // en-US/View.cshtml
                contents = provider.GetDirectoryContents(directory);
                IFileInfo dir = contents.FirstOrDefault(x => x.IsDirectory && x.Name.Equals(culture));
                if (dir != null)
                {
                    targetName = $"{fileName}.{extension}";
                    filePath   = $"{directory}/{culture}/{targetName}";
                    file       = provider.GetFileInfo(filePath);
                    if (file.Exists && !file.IsDirectory)
                    {
                        result = new FileCultureInfo(filePath, targetName, fileName, extension, requestedCulture);
                        return(true);
                    }
                }

                // find by language
                // View.en.cshtml
                culture    = requestedCulture.Language;
                targetName = $"{fileName}.{culture}.{extension}";
                filePath   = $"{directory}/{targetName}";
                file       = provider.GetFileInfo(filePath);
                if (file.Exists && !file.IsDirectory)
                {
                    result = new FileCultureInfo(filePath, targetName, fileName, extension, culture.ParseCultureExpression());
                    return(true);
                }

                // try find directory named with the specific language
                // en/View.cshtml
                dir = contents.FirstOrDefault(x => x.IsDirectory && x.Name.Equals(culture));
                if (dir != null)
                {
                    targetName = $"{fileName}.{extension}";
                    filePath   = $"{directory}/{culture}/{targetName}";
                    file       = provider.GetFileInfo(filePath);
                    if (file.Exists && !file.IsDirectory)
                    {
                        result = new FileCultureInfo(filePath, targetName, fileName, extension, culture.ParseCultureExpression());
                        return(true);
                    }
                }
            }

            result = null;
            return(false);
        }
Example #17
0
        /// <summary>
        /// Adds version query parameter to the specified file path.
        /// </summary>
        /// <param name="path">The path of the file to which version should be added.</param>
        /// <returns>Path containing the version query string.</returns>
        /// <remarks>
        /// The version query string is appended with the key "v".
        /// </remarks>
        public string AddFileVersionToPath(string path, string mappedPath)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (mappedPath == null)
            {
                throw new ArgumentNullException(nameof(mappedPath));
            }

            var resolvedPath = mappedPath;

            var queryStringOrFragmentStartIndex = path.IndexOfAny(QueryStringAndFragmentTokens);

            if (queryStringOrFragmentStartIndex != -1)
            {
                resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex);
            }

            Uri uri;

            if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out uri) && !uri.IsFile)
            {
                // Don't append version if the path is absolute.
                return(path);
            }

            string value;

            if (!_cache.TryGetValue(path, out value))
            {
                var cacheEntryOptions = new MemoryCacheEntryOptions();
                cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(resolvedPath));
                var fileInfo = _fileProvider.GetFileInfo(resolvedPath);

                if (!fileInfo.Exists &&
                    _requestPathBase.HasValue &&
                    resolvedPath.StartsWith(_requestPathBase.Value, StringComparison.OrdinalIgnoreCase))
                {
                    var requestPathBaseRelativePath = resolvedPath.Substring(_requestPathBase.Value.Length);
                    cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(requestPathBaseRelativePath));
                    fileInfo = _fileProvider.GetFileInfo(requestPathBaseRelativePath);
                }

                if (fileInfo.Exists)
                {
                    value = QueryHelpers.AddQueryString(path, VersionKey, GetHashForFile(fileInfo));
                }
                else
                {
                    // if the file is not in the current server.
                    value = path;
                }

                value = _cache.Set <string>(path, value, cacheEntryOptions);
            }

            return(value);
        }
Example #18
0
 public static IFileInfo GetAirlineNames() => fileProvider.GetFileInfo("AirlineNames.xml");
 public IFileInfo GetFileInfo(string subpath)
 => _other.GetFileInfo(Path.Combine(_path, subpath));
Example #20
0
 public virtual IFileInfo GetFileInfo(string subpath)
 {
     return(_hybridFileProvider.GetFileInfo(subpath));
 }
 public IEnumerable <IFileInfo> GetLocations(string cultureName)
 {
     return(fileProvider.GetDirectoryContents(resourcesContainer)                                                       // Localisation/CatalogueScanner.Core, Localisation/CatalogueScanner.SaleFinder, ...
            .Where(f => f.IsDirectory)
            .Select(dir => fileProvider.GetFileInfo(Path.Combine(resourcesContainer, dir.Name, $"{cultureName}.po")))); // Localisation/CatalogueScanner.Core/en.po, Localisation/CatalogueScanner.SaleFinder/en.po, ...
 }
Example #22
0
        public bool FileExists(string virtualPath)
        {
            var file = _fileProvider.GetFileInfo(virtualPath);

            return(file.Exists);
        }
 public static Stream ReadAsStream(this IFileProvider fileProvider, string subpath)
 {
     return(fileProvider.GetFileInfo(subpath).CreateReadStream());
 }
Example #24
0
 public IFileInfo GetImageOriginal()
 {
     return(fileProvider.GetFileInfo(imageSizeInfo.OriginalPath));
 }
Example #25
0
 public static string GetRoot(this IFileProvider provider)
 {
     return(provider.GetFileInfo("/").PhysicalPath);
 }
Example #26
0
 /// <summary>
 /// Locate a file at the give relative paths
 /// </summary>
 public static IFileInfo GetRelativeFileInfo(this IFileProvider provider, string path, string other = null)
 {
     return(provider.GetFileInfo(PathExtensions.ResolvePath(PathExtensions.Combine(path, other))));
 }
Example #27
0
        internal ResolveFilePathResult ResolveFilePath(IFileProvider fileProvider)
        {
            // Let the file system try to get the file and if it can't,
            // fallback to trying the path directly unless the path starts with '/'.
            // In that case we consider it relative and won't try to resolve it as
            // a full path

            var path = NormalizePath(FileName);

            // Note that we cannot use 'File.Exists' check as the file could be a non-physical
            // file. For example, an embedded resource.
            if (IsPathRooted(path))
            {
                // The path is absolute
                // C:\...\file.ext
                // C:/.../file.ext
                return new ResolveFilePathResult()
                {
                    PhysicalFilePath = path
                };
            }

            var fileInfo = fileProvider.GetFileInfo(path);
            if (fileInfo.Exists)
            {
                // The path is relative and IFileProvider found the file, so return the full
                // path.
                return new ResolveFilePathResult()
                {
                    // Note that physical path could be null in case of non-disk file (ex: embedded resource)
                    PhysicalFilePath = fileInfo.PhysicalPath,
                    FileInfo = fileInfo
                };
            }

            // We are absolutely sure the path is relative, and couldn't find the file
            // on the file system.
            var message = Resources.FormatFileResult_InvalidPath(path);
            throw new FileNotFoundException(message, path);
        }
Example #28
0
 private string MapStorage(string path)
 {
     return(_fileProvider.GetFileInfo(path).PhysicalPath);
     //return path;
 }
        private static string ReadFileContentsSafely(IFileProvider fileProvider, string filePath)
        {
            var fileInfo = fileProvider.GetFileInfo(filePath);
            if (fileInfo.Exists)
            {
                try
                {
                    using (var reader = new StreamReader(fileInfo.CreateReadStream()))
                    {
                        return reader.ReadToEnd();
                    }
                }
                catch
                {
                    // Ignore any failures
                }
            }

            return null;
        }
        public IFileInfo GetFileInfo(string subpath)
        {
            var fileInfo = _compositeFileProvider.GetFileInfo(subpath);

            return(fileInfo);
        }