c# - C# ASP 目录存在时为真
问题描述
我在检查Directory.Exists
目录不存在时始终返回 true 时遇到问题。至少这些是我基于错误日志的假设。
注意:问题不是在本地开发环境中发生,仅在生产环境中发生。
因此,首先,这是错误消息:
Message: Could not find a part of the path 'd:\home\site\wwwroot\media\cdn'.
Exception type: System.IO.DirectoryNotFoundException
Stack Trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.CommonInit()
at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
at System.IO.Directory.GetFiles(String path, String searchPattern)
at CMS.AzureStorage.Directory.GetFiles(String path, String searchPattern)
at CMS.IO.Directory.GetFiles(String path, String searchPattern)
at CMS.AzureStorage.DirectoryInfo.GetFiles(String searchPattern, SearchOption searchOption)
相关功能(精简为相关代码):
public override string[] GetFiles(string path, string searchPattern)
{
List<string> stringList = new List<string>();
if (Directory.ExistsInFileSystem(path))
{
foreach (string file in System.IO.Directory.GetFiles(path, searchPattern))
stringList.Add(Directory.GetCaseValidPath(file, new bool?()));
}
...
}
public static bool ExistsInFileSystem(string path)
{
return System.IO.Directory.Exists(path);
}
如您所见,它正在到达System.IO.Directory.GetFiles
,但我不明白的是if (Directory.ExistsInFileSystem(path))
,当目录不存在时,该行是如何被绕过的?
我很困惑,希望有人能解释发生了什么。
解决方案
您正在尝试访问站点根文件夹之外的文件夹。
如果生产环境是“云”,那么您需要提供对目录的访问权限。
提供访问取决于您的云环境
- 如果您使用的是 VM,那么您可以直接转到 IIS 并提供目录访问权限。
- 对于其他模型,您需要通过代码提供访问权限。
下面是提供对 wwwroot 文件夹的读写访问权限的代码。您可以在以下代码之后调用您的代码
string file = @"d:\home\site\wwwroot";
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
推荐阅读
- corda - 如何在不重新部署节点的情况下创建 CorDapp jar 文件?
- java - jSerialComm - SerialPortEvent.getReceivedData() 在收到 Arduino 消息时返回 null
- google-cloud-platform - Google Cloud Console - 通过克隆设置 VM 实例
- azure - Azure asp.net core 2.2 获得高 CPU 使用率
- java - 同步多个线程之间的状态
- spring-boot - Spring Boot & RabbitMQ:消息转换内容类型
- javascript - 将 React 添加到工作区失败,EACCES:权限被拒绝,mkdir '/home/mint/.cache/Cypress'
- foreign-keys - Javers - 外键约束因 mysql 而失败
- mysql - 将空白单元格更新为 NULL 会导致所有单元格为 NULL
- java - 如何解决 maven-formatter-plugin 的问题?