首页 > 解决方案 > 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)),当目录不存在时,该行是如何被绕过的?

我很困惑,希望有人能解释发生了什么。

标签: c#asp.netkentico

解决方案


您正在尝试访问站点根文件夹之外的文件夹。
如果生产环境是“云”,那么您需要提供对目录的访问权限。
提供访问取决于您的云环境

  1. 如果您使用的是 VM,那么您可以直接转到 IIS 并提供目录访问权限。
  2. 对于其他模型,您需要通过代码提供访问权限。

下面是提供对 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);

推荐阅读