繁体   English   中英

尝试保存文件:Directory.Exists()在目录实际不在目录中时返回true

[英]Trying to save a file: Directory.Exists() returning true when directories aren't actually there

因此,我有一个HTML表单,用户可以在其中上传图像。 这将发布到我的操作中,图像将放入用户ID唯一的目录中(如果该目录不存在,则会创建该目录)。

自从大约两个月前实施以来,这种方法一直很好,而且从此我就不必再去碰它了。 最初,我遇到了UnauthorizedAccessExceptions但是通过进入上载目录的安全设置并将完全控制权授予“所有人”来解决。

好吧,我再也无法保存图像了。 尽管再次更改了文件夹的安全设置以尝试对其进行修复,但我还是再次开始获得UnauthorizedAccessExceptions 最后阅读有关在ASP.net中进行帐户模拟的信息。

因此,现在我没有收到UnauthorizedAccessExceptions ,而是遇到目录已存在的问题。

这是我的表单操作的摘录:

if (Directory.Exists(Path.GetDirectoryName(Server.MapPath("../uploads/" + currentUser.UserId))) == false)
{
   Directory.CreateDirectory(Path.GetDirectoryName("../uploads/" + currentUser.UserId));
}
if (Directory.Exists(Path.GetDirectoryName(Server.MapPath("../uploads/" + currentUser.UserId + "/" + newEntry.EntryId))) == false)
{
   Directory.CreateDirectory(Path.GetDirectoryName("../uploads/" + currentUser.UserId + "/" + newEntry.EntryId));
}

ImageFile.SaveAs(Server.MapPath("../" + savedFileName));

if语句中的代码从不执行。 因此,我删除了它们并尝试:

Directory.CreateDirectory(Path.GetDirectoryName("../uploads/" + currentUser.UserId));

什么都没发生! 然后,当需要保存图像时,由于目录不存在,我引发了异常! 谁能告诉我为什么Directory.Exists()返回true ,或者为什么Directory.CreateDirectory()绝对不执行任何操作?

还是为什么这段代码没有被修改并且可以正常工作几个月,却突然决定放弃呢?

注意:如果我转到该文件夹​​并手动创建目录,则文件保存就可以了

Path.GetDirectoryName仅返回目录名称,而不是目录的标准路径。 Directory.Exists将采用目录的标准路径,然后检查目录是否存在。

如果作为Directory.Exists,您的条件将失败。Exists将在Web应用程序的根目录中检查该文件夹是否存在,而不是查看上载文件夹。

您的情况应如下所示:

if (Directory.Exists(Server.MapPath("/uploads/" + currentUser.UserId)) == false)
{
    Directory.CreateDirectory(Server.MapPath("/uploads/" + currentUser.UserId));
}

注意:从路径中删除了开头的“ ..”,它起作用了!!

显然,这就是我需要更改的所有内容:

Directory.CreateDirectory(Server.MapPath("../uploads/" + currentUser.UserId));

放入Server.MapPath,现在一切正常。 不知道为什么它之前运行良好并突然停止。

尝试这个:

var path = Server.MapPath(string.Format("~/uploads/{0}/{1}/", userId, entryId));

//MSDN: Creates all directories and subdirectories as specified by path
Directory.CreateDirectory(path);

var filePath = Path.Combine(path, savedFileName);

ImageFile.SaveAs(filePath );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM