【问题标题】:How Can I Use File.Create Web Path as Parameter at .Net Core如何在 .Net Core 中使用 File.Create Web 路径作为参数
【发布时间】:2020-07-06 15:16:49
【问题描述】:

版本 .NetCore 2.1 IIS 上有一个共享路径,例如 h ttps://foo.com/bar" IIS 我的网站上的这个 bar 文件夹

http-s://mysite.com/bar/request 返回状态码 200

如果 targetFilePath 为“z:\myfiles\cookieRecipe.txt”,则此代码将成功。

但如果 targetFilePath 是 "http-s://mysite.com/bar/cookieRecipe.txt" 这会抛出一个异常,例如 "System.IO.IOException","HResult":-2147024773 ,"Message":"文件名、目录名或卷标语法不正确Z:\Publish\MyWeb.Web\http-s:\mysite.com\bar" 为什么会这样代码添加 Z:\Publish\MyWeb.Web 到我的路径?我该如何解决?

  using (var targetStream = File.Create(targetFilePath))
  {
     await item.CopyToAsync(targetStream);
  }

【问题讨论】:

  • 1) “http-s://mysite.com/bar/cookieRecipe.txt”是无效路径。 2) .NET Core 尝试根据您的无效输入(添加基本路径)计算另一个路径,这成为另一个无效路径并导致另一个失败。如何解决?提供有效的文件路径。
  • 那是物理路径。你需要虚拟路径,在asp.net mappath中。从私有只读 IApplicationEnvironment _env 收集它;公共 HomeController(IApplicationEnvironment appEnvironment) { _env = env; } public ActionResult Index() { return Content(_env.ApplicationBasePath); }
  • 检索 ApplicationBasePath

标签: c# iis .net-core file-upload


【解决方案1】:

文档解释说file.open(path)只支持相对或绝对路径。相对路径信息被解释为相对于当前工作目录

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.create?view=netcore-3.1

如果您想从远程读取内容,请改用 webclient。

  WebClient client = new WebClient();
            Stream stream = client.OpenRead("https://mysite/a");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();

【讨论】:

    猜你喜欢
    • 2013-06-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2021-12-11
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多