public async Task <IActionResult> Index() { // ルートフォルダ(=スコープ)を指定してファイルプロバイダを生成 var fileProvider = new PhysicalFileProvider(@"c:\temp"); // IFileInfoを取得して var foundFile = fileProvider.GetFileInfo("test.txt"); // ファイルの存在チェックができたり Debug.WriteLine(foundFile.Exists); // True // ファイルの内容を読み込んだり if (foundFile.Exists) { using var stream = foundFile.CreateReadStream(); using var reader = new StreamReader(stream); var text = await reader.ReadToEndAsync(); } // スコープ外のファイルには存在していてもアクセスできない var notFoundFile = fileProvider.GetFileInfo("c:\test.txt"); Debug.WriteLine(notFoundFile.Exists); // False // 戻り値はNotFoundFileInfoというクラス Debug.WriteLine(notFoundFile.GetType()); // Microsoft.Extensions.FileProviders.NotFoundFileInfo return(new EmptyResult()); }
public IFileInfo WriteFile(string xmlString, DirectoryInfo targetDirectory, string targetFileName) { if (!targetDirectory.Exists) { targetDirectory.Create(); } var fullPath = Path.Combine(targetDirectory.FullName, targetFileName); if (File.Exists(fullPath)) { File.Delete(fullPath); } var provider = new PhysicalFileProvider(targetDirectory.FullName); var fileInfo = provider.GetFileInfo(targetFileName); if (fileInfo.Exists) { File.Delete(fileInfo.PhysicalPath); } File.WriteAllText(fullPath, xmlString); return(provider.GetFileInfo(targetFileName)); }
public Task <ISitemapCacheFileResolver> GetCachedSitemapAsync(string cacheFileName) { var fileInfo = _fileProvider.GetFileInfo(cacheFileName); if (fileInfo.Exists) { return(Task.FromResult <ISitemapCacheFileResolver>(new PhysicalSitemapCacheFileResolver(fileInfo))); } return(Task.FromResult <ISitemapCacheFileResolver>(null)); }
static void Main(string[] args) { ETL.Instance.Do(@"D:\Work\DMS\src\tests\ETL\test.json"); var root = Directory.GetCurrentDirectory(); var fileProvider = new PhysicalFileProvider(root); var tocXml = fileProvider.GetFileInfo("/toc.xml"); NCX ncx = new NCX() { head = new List<metaData>(), docTitle = new docText() { text = "test" }, navMap = new List<navPoint>(), }; File.WriteAllText(tocXml.PhysicalPath, XmlSerialize<NCX>(ncx)); return; var toc = fileProvider.GetFileInfo("/toc.ncx"); if (!toc.Exists) { File.Create(toc.PhysicalPath).Dispose(); } using (var stream = toc.CreateReadStream()) { // XmlDocument doc = new XmlDocument(); // XmlReaderSettings xmlReaderSettings = new XmlReaderSettings // { // DtdProcessing = DtdProcessing.Ignore // }; // using (XmlReader xmlReader = XmlReader.Create(stream, xmlReaderSettings)) // { // doc.Load(xmlReader); // } // Xml.Net.XmlConvert //var metas = doc.DocumentElement.GetElementsByTagName("meta"); // var docTitle = doc.GetElementsByTagName("docTitle")[0]; // var navPoint = doc.GetElementsByTagName("navPoint"); } foreach (var item in fileProvider.GetDirectoryContents("/")) { if (item.IsDirectory) { } }; Console.WriteLine(root); Console.WriteLine(string.Join("\r\n", args)); Console.Read(); }
public MarkdownProvider(string repository) { this.path = Path.Combine(repository, "content"); this.source = new PhysicalFileProvider(path, ExclusionFilters.Sensitive); converter = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build(); changes = source.Watch("*.md"); changes.RegisterChangeCallback(o => OnSourceChanged(), changes); header = source.GetFileInfo("header.html"); footer = source.GetFileInfo("footer.html"); lock (renderedPages) { renderDirectory(new DirectoryInfo(path)).GetAwaiter().GetResult(); } }
public async Task <IActionResult> logPreview(string fileName) { if (!await HasLogin()) { return(RedirectToAction("Index")); } if (!Regex.IsMatch(fileName, @"^[0-9a-z-_.]+[log|txt]$", RegexOptions.IgnoreCase)) { return(RedirectToAction("Index")); } var fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); var file = fileProvider.GetFileInfo($"/logs/{fileName}"); string txtData = null; Stream stream = file.CreateReadStream(); using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default)) { txtData = await sr.ReadToEndAsync(); sr.Close(); } ContentResult rs = new ContentResult(); rs.Content = txtData; rs.ContentType = "text/plain"; return(rs); }
public bool DeleteVideo(News news) { var deleted = false; try { TimesOfLebanonContext dbContext = new TimesOfLebanonContext(); //var rootPath = hostingEnvironment.ContentRootPath; var wwwPath = hostingEnvironment.WebRootPath; var videoPath = news.VideoPath.Replace(_baseURL, ""); //videoPath = videoPath.Replace("/", "\\"); //var physicalPath = wwwPath + videoPath; var provider = new PhysicalFileProvider(wwwPath); var fileInfo = provider.GetFileInfo(videoPath); if (fileInfo.Exists) { System.IO.File.Delete(fileInfo.PhysicalPath); dbContext.DeleteVideo(news.Id); deleted = true; } } catch (Exception ex) { var _User = HttpContext.Session.GetObjectFromJson <Users>("User"); HandleException(_User.UserId, "DeleteVideo", ex); } return(deleted); }
public static void Main(string[] args) { var cache = new MemoryCache(new MemoryCacheOptions()); var greeting = ""; var cacheKey = "cache_key"; var fileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "WatchedFiles")); do { if (!cache.TryGetValue(cacheKey, out greeting)) { using (var streamReader = new StreamReader(fileProvider.GetFileInfo("example.txt").CreateReadStream())) { greeting = streamReader.ReadToEnd(); cache.Set(cacheKey, greeting, new MemoryCacheEntryOptions() //Telling the cache to depend on the IChangeToken from watching examples.txt .AddExpirationToken(fileProvider.Watch("example.txt")) .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine($"{echoKey} : {value} was evicted due to {reason}"); })); Console.WriteLine($"{cacheKey} updated from source."); } } else { Console.WriteLine($"{cacheKey} retrieved from cache."); } Console.WriteLine(greeting); Console.WriteLine("Press any key to continue. Press the ESC key to exit"); }while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
static async Task FileWatcher() { using var fileProvider = new PhysicalFileProvider(@"D:\Dev\InAspNetCore\InAspNetCore3\FileSystem\Test"); string original = null; ChangeToken.OnChange(() => fileProvider.Watch("data.txt"), Callback); while (true) { await File.WriteAllTextAsync(@"D:\Dev\InAspNetCore\InAspNetCore3\FileSystem\Test\data.txt", DateTime.Now.ToString(CultureInfo.InvariantCulture)); await Task.Delay(5000); } async void Callback() { await using var stream = fileProvider.GetFileInfo("data.txt").CreateReadStream(); var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); string current = Encoding.Default.GetString(buffer); if (current != original) { original = current; Console.WriteLine(original); } } }
public async void WatchFile(string filePath) { using (var fileProvider = new PhysicalFileProvider(filePath)) { string original = null; ChangeToken.OnChange(() => fileProvider.Watch("data.txt"), Callback); while (true) { File.WriteAllText(@"c:\test\data.txt", DateTime.Now.ToString()); await Task.Delay(5000); } async void Callback() { var stream = fileProvider.GetFileInfo("data.txt").CreateReadStream(); { var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); string current = Encoding.Default.GetString(buffer); if (current != original) { Console.WriteLine(original = current); } } } } }
/// <summary> /// 初期化 /// </summary> /// <param name="postjson"></param> /// <returns></returns> public JsonResult OnPostInit([FromBody] JToken postjson) { //テストデータの取得 // FileProviderを作成 IFileProvider provider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); // アプリケーションルートの要素を取得 //IDirectoryContents contents = provider.GetDirectoryContents(""); // アプリケーションルート下のファイルを取得 IFileInfo fileInfo = provider.GetFileInfo("wwwroot/testdata/chugoku.json"); System.IO.StreamReader sr = new System.IO.StreamReader( fileInfo.PhysicalPath, System.Text.Encoding.UTF8); //内容をすべて読み込む string s = sr.ReadToEnd(); //閉じる sr.Close(); var todofuken = (JToken)JsonConvert.DeserializeObject(s); //var json = JsonSerializer. JObject json = new JObject(); json.Add("todofuken", todofuken); //複数必要な場合はaddする //json.Add("xxx", yyyy); return(new JsonResult(json)); }
public async Task ExecuteResult(Controller controller) { var contentTypeProvider = new FileExtensionContentTypeProvider(); var response = controller.Context.Response; if (string.IsNullOrWhiteSpace(ContentType)) { if (!string.IsNullOrEmpty(response.ContentType)) { ContentType = response.ContentType; } else if (contentTypeProvider.TryGetContentType(Path, out var resolvedContentType)) { ContentType = resolvedContentType; } else { ContentType = _defaultContentType; } } response.ContentType = ContentType; if (StatusCode != null) { response.StatusCode = StatusCode.Value; } using (var fileStream = FileProvider.GetFileInfo(Path).CreateReadStream()) { response.ContentLength = fileStream.Length; await fileStream.CopyToAsync(response.Body); } await response.CompleteAsync(); }
private FileResult DownloadPDF(string filePath) { if (string.IsNullOrEmpty(filePath)) { return(null); } var dir = Path.Combine(Globals.CartellaWEBMVA, "wwwroot", Path.GetDirectoryName(filePath)); var fileName = Path.GetFileName(filePath); var extension = Path.GetExtension(fileName).ToLower(); string percorsoAssolutoPDF; if (extension.Equals(".xml")) { percorsoAssolutoPDF = Globals.ConvertiReportXML(Path.Combine(dir, fileName)); } else if (extension.Equals(".txt")) { percorsoAssolutoPDF = Globals.ConvertiReportTXT(Path.Combine(dir, fileName)); } else { return(null); //per ora } fileName = Path.GetFileName(percorsoAssolutoPDF); IFileProvider provider = new PhysicalFileProvider(dir); IFileInfo fileInfo = provider.GetFileInfo(fileName); var readStream = fileInfo.CreateReadStream(); string mimetype = "application/pdf"; return(File(readStream, mimetype, fileName)); }
public static void ConfigureKestrel(WebHostBuilderContext context, KestrelServerOptions options) { var rootPath = context.Configuration.GetSection("SMEIoT")?.GetValue <string>("SystemFilesRoot"); if (rootPath == null) { return; } var provider = new PhysicalFileProvider(rootPath); var unixSocketFileInfo = provider.GetFileInfo("smeiot.auth.broker"); if (unixSocketFileInfo.Exists) { File.Delete(unixSocketFileInfo.PhysicalPath); } if (context.Configuration.GetSection("SMEIoT")?.GetValue <bool>("UseMosquittoBackgroundClient") == true) { options.ListenUnixSocket(unixSocketFileInfo.PhysicalPath, builder => { builder.Protocols = HttpProtocols.None; builder.UseConnectionHandler <MosquittoBrokerAuthHandler>(); }); } }
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()); }
// GET: Export Gear Box public FileResult GearBoxExport() { // List <GearBox> lstGearBox = new List <GearBox>(); try { lstGearBox = GetData(); } catch (Exception) { lstGearBox = null; } string sWebRootFolder = _hostingEnvironment.ContentRootPath + "\\FilesUpload"; CreateExport(lstGearBox, sWebRootFolder); string fPath = sWebRootFolder + "\\" + "DanhSachHopSo.xlsx"; FileInfo fi = new FileInfo(fPath); IFileProvider provider = new PhysicalFileProvider(sWebRootFolder); string fileName = @"DanhSachHopSo.xlsx"; IFileInfo fileInfo = provider.GetFileInfo(fileName); var readStream = fileInfo.CreateReadStream(); var mimeType = "application/vnd.ms-excel"; return(File(readStream, mimeType, fileName)); //return File(fPath, System.Net.Mime.MediaTypeNames.Application.Octet, "DanhSachHopSo" + fi.Extension); }
/// <summary> /// CSVを読み込む /// </summary> /// <param name="directry">ディレクトリ</param> /// <param name="filename">拡張子付きのファイル名</param> /// <returns></returns> private List <string[]> ReadCsv(string directry, string filename = "file.csv") { // ファイルの読み込み List <string[]> csv = null; using (PhysicalFileProvider provider = new PhysicalFileProvider(directry)) { // ファイル情報を取得 IFileInfo fileInfo = provider.GetFileInfo(filename); // ファイル存在チェック if (fileInfo.Exists) { csv = new List <string[]>(); // 改行コード、コンマで分けて格納する var data = File.ReadAllText(fileInfo.PhysicalPath); data = data.Replace("\r\n", "\n"); data = data.Replace("\r", "\n"); data = data.Trim('\n'); var lines = data.Split('\n'); foreach (var item in lines) { csv.Add(item.Split(',')); } } else { return(new List <string[]>()); } } return(csv); }
private IFileInfo GetFileInfo(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } List <string> patterns = new List <string> { key, $"Shared/{key}" }; if (key.StartsWith("/Views/")) { patterns.Add(key.Substring("/Views/".Length)); } var fileInfos = patterns.Select(p => fileProvider.GetFileInfo(p)); IFileInfo fileInfo = (from p in fileInfos where p.Exists select p).FirstOrDefault() ?? fileInfos.FirstOrDefault(); if (!fileInfo.Exists || fileInfo.IsDirectory) { throw new FileNotFoundException("Can't find a file with a specified key", key); } return(fileInfo); }
public static string GetSecretOrEnvVarAsString(string key, ILogger logger) { try { string configPath = GetConfigPath(); IFileProvider provider = new PhysicalFileProvider(configPath); IFileInfo fileInfo = provider.GetFileInfo(key); if (fileInfo.Exists) { using (var stream = fileInfo.CreateReadStream()) using (var streamReader = new StreamReader(stream)) { return(streamReader.ReadToEnd()); } } } catch (Exception ex) { logger.LogError("Error getting environment variable: " + key + " (" + ex.Message + ")"); return(string.Empty); } return(string.Empty); }
private string GetConnectionString() { const string name = "DockThisDbConnection"; string connectionString = null; var dirs = Directory.GetDirectories(Directory.GetCurrentDirectory()); var dirs0 = Directory.GetDirectories("/"); var dirs1 = Directory.GetDirectories("../"); var dirs2 = Directory.GetDirectories("../run"); #if DEBUG connectionString = Configuration[name]; #else const string dockerSecretsPath = "/run/secrets/"; if (Directory.Exists(dockerSecretsPath)) { IFileProvider provider = new PhysicalFileProvider(dockerSecretsPath); IFileInfo fileInfo = provider.GetFileInfo(name); if (fileInfo.Exists) { using (var stream = fileInfo.CreateReadStream()) using (var streamReader = new StreamReader(stream)) { connectionString = streamReader.ReadToEnd(); } } } #endif if (string.IsNullOrEmpty(connectionString)) { throw new Exception($"Could not find connection string under '{name}'"); } return(connectionString); }
public IFileInfo GetFileInfo(string path) { path = path.Replace("/", "\\"); if (path.StartsWith("\\")) { path = path.Substring(1, path.Length - 1); } ; if (!path.StartsWith("DnDoc")) { path = Path.Combine("wwwroot", path); bool isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); if (isLinux) { path = path.Replace("/", "\\"); } var provider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); var fileInfo = provider.GetFileInfo(path); return(fileInfo); } path = path.Replace("/", ".").Replace("\\", "."); return(EmbeddedFileProvider.GetFileInfo(path)); }
public static async Task <IActionResult> RunWithoutRange( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); log.LogInformation($"[{req.Method}] {req.Path}, " + $"Header: {JsonConvert.SerializeObject(req.Headers/*, Formatting.Indented*/)}, " + $"Query: {JsonConvert.SerializeObject(req.Query/*, Formatting.Indented*/)}"); ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() //.SetBasePath(Directory.GetCurrentDirectory()) //.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); var pathToVideos = config.DataDirectory; var file = config.TargetFileName; using var provider = new PhysicalFileProvider(pathToVideos); IFileInfo fileInfo = provider.GetFileInfo(file); var contentType = GetType(fileInfo.PhysicalPath); log.LogInformation($"File: {fileInfo.PhysicalPath}"); /*await using*/ var oStream = fileInfo.CreateReadStream(); return(new FileStreamResult(oStream, contentType)); }
private string GetPhysicalPath(string path) { var provider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory())); var fileInfo = provider.GetFileInfo(path); return(fileInfo.PhysicalPath); }
public IFileInfo GetFileInfo(string subpath) { IFileInfo file = null; if (_physicalFileProvider != null) { file = _physicalFileProvider.GetFileInfo(subpath); } if (file == null || !file.Exists) { file = _embeddedFileProvider.GetFileInfo(subpath); if (!file.Exists) { // To support some file paths we need to fix it by removing dashes in the directory // which aren't translated well by the underlying provider. var fileName = Path.GetFileName(subpath); var directory = subpath.Remove(subpath.Length - fileName.Length); var fixedName = directory.Replace("-", "_") + fileName; file = _embeddedFileProvider.GetFileInfo(fixedName); } } return(file); }
/* * 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); } }
public IFileInfo WriteFile(string xmlString, DirectoryInfo targetDirectory, string targetFileName) { var provider = new PhysicalFileProvider(targetDirectory.FullName); var file = provider.GetFileInfo(targetFileName); return(file); }
public async Task <FileResult> ExportExcel(DateTime?fromDate, DateTime?toDate) { // List <DataStatisticsDTO> dataStatisticsDTOs = new List <DataStatisticsDTO>(); try { dataStatisticsDTOs = await GetData(fromDate, toDate); } catch (Exception) { dataStatisticsDTOs = null; } string sWebRootFolder = _hostingEnvironment.ContentRootPath + "\\FilesUpload"; CreateExport(dataStatisticsDTOs, sWebRootFolder); string fPath = sWebRootFolder + "\\" + "ThongKeTongQuat.xlsx"; FileInfo fi = new FileInfo(fPath); IFileProvider provider = new PhysicalFileProvider(sWebRootFolder); string fileName = @"ThongKeTongQuat.xlsx"; IFileInfo fileInfo = provider.GetFileInfo(fileName); var readStream = fileInfo.CreateReadStream(); var mimeType = "application/vnd.ms-excel"; return(File(readStream, mimeType, fileName)); //return File(fPath, System.Net.Mime.MediaTypeNames.Application.Octet, "ThongKeTongQuat" + fi.Extension); }
private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).GetAsync(); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); Assert.NotNull(response.Headers.ETag); using (var stream = fileInfo.CreateReadStream()) { var fileContents = new byte[stream.Length]; stream.Read(fileContents, 0, (int)stream.Length); Assert.True(responseContent.SequenceEqual(fileContents)); } } }
public IActionResult GetPdf(int id) { var query = _context.Invoices.Include(i => i.Rows) .Include(i => i.Client) .Include(i => i.PaymentType) .SingleOrDefault(i => i.InvoiceId == id); var exporter = new InvoicePdfExporter(); var content = exporter.Export(query); var pdfDoc = new Document(PageSize.A4); var fileName = $"{Guid.NewGuid()}.pdf"; var pdfFilePath = Path.Combine(Path.GetTempPath(), fileName); using (var fileStream = new FileStream(pdfFilePath, FileMode.Create)) { PdfWriter.GetInstance(pdfDoc, fileStream); pdfDoc.Open(); var chunk = new Paragraph(content); pdfDoc.Add(chunk); pdfDoc.Close(); fileStream.Dispose(); } var provider = new PhysicalFileProvider(Path.GetTempPath()); IFileInfo fileInfo = provider.GetFileInfo(fileName); var readStream = fileInfo.CreateReadStream(); return(File(readStream, "application/octet-stream")); }
private static string GetCheckSum(IConfiguration configuration) { var checksumConfiguration = configuration.GetSection(InfoManagementChecksumOptions.DefaultSectionName) .Get <InfoManagementChecksumOptions>() ?? new InfoManagementChecksumOptions(); if (!Directory.Exists(checksumConfiguration.Root)) { return(null); } var physicalFileProvider = new PhysicalFileProvider(checksumConfiguration.Root); var fileInfo = physicalFileProvider.GetFileInfo(checksumConfiguration.FilePath); if (!fileInfo.Exists) { return(null); } using (var stream = fileInfo.CreateReadStream()) { using (var reader = new StreamReader(stream)) { return(reader.ReadToEnd().Trim()); } } }