如何将文件保存在 asp.net 中应用程序文件夹外部的 IIS 文件夹中

How can i save files in folder within the IIS of outside of the Application folder in asp.net

在我的 Web 应用程序中,我有一些文件保存在应用程序中,它正在创建一个用于保存文件的文件夹,但我需要将这些文件保存在应用程序外部和 IIS[=19= 内部]。我怎样才能做到这一点? 在应用程序文件夹中,我们使用以下代码

Server.MapPath(Path) 

在IIS中保存如何写?

谢谢

您需要创建一个指向文件夹外部的虚拟目录。 转到 IIS,右键单击您的网站。从 menu.Give 目录 select 的别名单击所需文件夹中的“添加虚拟目录”,即可完成。它会将这个外部文件夹视为内部文件夹并以相同的方式工作。检查这个 link How to: Create and Configure Virtual Directories in IIS 7.0

免责声明:但您必须在托管到 iis 后执行此操作,即发布。在开发环境中使用 visual studio 时即调试它将仅存储在内部目录中

编辑:这是用于创建虚拟目录的代码。我没有测试过它的有效性。

static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
  //  metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
  //    for example "IIS://localhost/W3SVC/1/Root" 
  //  vDirName is of the form "<name>", for example, "MyNewVDir"
  //  physicalPath is of the form "<drive>:\<path>", for example,"C:\Inetpub\Wwwroot"


  try
  {
    DirectoryEntry site = new DirectoryEntry(metabasePath);
   string className = site.SchemaClassName.ToString();
  if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
  {
  DirectoryEntries vdirs = site.Children;
  DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir")));
  newVDir.Properties["Path"][0] = physicalPath;
  newVDir.Properties["AccessScript"][0] = true;
  // These properties are necessary for an application to be created.
  newVDir.Properties["AppFriendlyName"][0] = vDirName;
  newVDir.Properties["AppIsolated"][0] = "1";
  newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));

  newVDir.CommitChanges();


}
else

  }
 catch (Exception ex)
 {

 }
}

通常您不能在根路径之外创建文件夹,即如果您的应用程序位于 C:\inetpub\testapp 中,您只能在 testapp 中创建文件夹。此限制是出于安全原因,网络服务器不应允许访问根文件夹以上的任何内容。

此外,不建议在根文件夹中写入任何 folders/files,因为写入根文件夹会导致 appdomain 在写入一定次数(默认为 15)后回收,从而导致会话丢失。 .

但是有一个解决方法

将您的服务器路径添加到 web.config,然后在您的 code.Use 中获取它,如下面 web.config

的应用程序设置部分
<add key="logfilesPath" value="C:\inetpub\MyAppLogs" />

创建上述路径的文件夹并将 Users 组添加到您的文件夹并授予该组完全权限 (read/write)。 (添加权限很重要)

在您的代码中,您可以如下获取

string loggerPath = (ConfigurationManager.AppSettings["logfilesPath"]);

希望对您有所帮助