【问题标题】:Access to the path ... is denied during fileupload in .net在 .net 中的文件上传期间访问路径 ... 被拒绝
【发布时间】:2015-08-20 09:44:28
【问题描述】:

我无法在 .net c# 中上传文件。我正在使用以下代码:

try
{
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
         var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Resources");                    
         var dataStream = await file.ReadAsStreamAsync();
         FileStream fileStream = File.Create(mappedPath, (int)dataStream.Length);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain");
    response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"text/html");
    return response;
}
catch (Exception e)
{
     return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}

这发生在本地主机上。 我有“访问路径......被拒绝”错误。我试图更改文件夹“资源”的安全权限,但可能我不知道要添加完全控制的组/用户名。

我试过了:

  1. 选择计算机名并添加网络服务 - 完全控制
  2. 选择计算机名并添加 IIS_IUSERS - 完全控制
  3. 我已经尝试了以上所有方法,并且还以管理员身份运行 IDE

【问题讨论】:

  • 看起来您只是将文件夹路径指定为 create 方法的参数。它需要一个文件的路径。
  • 哪一行抛出异常?

标签: c# .net file-upload


【解决方案1】:

在您的 foreach 循环中,您有:

foreach (var file in provider.Contents)
    {
         var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Resources");                    
         var dataStream = await file.ReadAsStreamAsync();
         FileStream fileStream = File.Create(mappedPath, (int)dataStream.Length);
    }

File.Create 的第一个参数应该是文件的路径,但您的 mappedPath 是目录的路径。你可以这样做:

var filePath = Path.Combine(mappedPath, fileNameWithExtension);
FileStream fileStream = File.Create(filePath, (int)dataStream.Length);

【讨论】:

    【解决方案2】:

    看起来您正在尝试使用 mappedPath 分配覆盖目录,这可能是实际原因,而不是权限。

    但是,就权限而言,鉴于您引用的是 IIS_IUSERS,您似乎是在 IIS 中工作。考虑为您的进程运行的身份授予写入权限;检查“进程模型”(应用程序池的高级设置)下的“身份”(IIS7+)设置 - 如果是 ApplicationPoolIdentity,您需要将该身份添加到文件夹的权限中。

    即,如果您的应用程序池名为 my-app.com,则本地用户将是 [iis apppool\my-app.com]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多