C# ServerManager.CommitChanges()引发错误:“无法写入配置文件”

C# ServerManager.CommitChanges()引发错误:“无法写入配置文件”,c#,iis,C#,Iis,下面是我创建应用程序的代码 public static bool CreateApplication(String websiteName, String applicationName, String AppDIR,String appPoolName) { try { var windowsDir = Environment.GetEnvironmentVariable("System

下面是我创建应用程序的代码

 public static bool CreateApplication(String websiteName, String applicationName, String AppDIR,String appPoolName)
        {
            try
            {
                var windowsDir = Environment.GetEnvironmentVariable("SystemRoot");
                Process.Start(windowsDir+@"\system32\inetsrv\appcmd","unlock config -section:system.webServer/security/authentication/windowsAuthentication");      
                Process.Start(windowsDir+@"\system32\inetsrv\appcmd","unlock config -section:system.webServer/security/authentication/anonymousAuthentication");

                ServerManager iisManager = new ServerManager();

                if (!applicationName.Contains("/"))
                    applicationName = "/" + applicationName;               

                var app = iisManager.Sites[websiteName].Applications.Add(applicationName, AppDIR);                             
                
                
                app.ApplicationPoolName = appPoolName;

                var config = app.GetWebConfiguration();
                var anonsection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", iisManager.Sites[websiteName].Name + applicationName);
                anonsection["enabled"] = false;

                var winsection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", iisManager.Sites[websiteName].Name + applicationName);
                winsection["enabled"] = true;

                iisManager.CommitChanges(); //Blows up here
                return true;
            }
            catch
            {
                return false;
            }
        }
在遇到commit changes方法调用之前,一切都正常

它抛出了这个错误

错误:无法写入配置文件

除了我将启用值更改为false和true之外,所有代码都被验证为正常工作

当我把这些加进去的时候,它开始爆炸

有没有办法从可以分发到其他机器的代码中修复此问题

更新: 重新锁定文件后

像这样

 Process.Start(windowsDir + @"\system32\inetsrv\appcmd", "lock config -section:system.webServer/security/authentication/windowsAuthentication");
 Process.Start(windowsDir + @"\system32\inetsrv\appcmd", "lock config -section:system.webServer/security/authentication/anonymousAuthentication");
我现在得到这个错误

错误:无法提交配置更改,因为文件已更改 在磁盘上更改


我还遇到了两个问题中的第二个错误:无法提交配置更改,因为c应用程序的磁盘上的文件已更改,我们使用该应用程序作为部署操作的一部分配置IIS服务器

对我来说,最终导致问题的原因是无意中使用围绕ServerManager对象的语句嵌套了两个


对于您的特殊情况,我会尝试添加一个using语句供您引用ServerManager,并确保命令行appcmd调用在using语句之外,或在using语句中移动,但通过ServerManager对象转换为API调用。

为什么同时使用appcmd和ServerManager?@haim770可以做到这一点考虑到我所经历的错误,真的会有所不同吗?如果是,请解释并提供解决方案。如果不是,那又有什么关系呢?这很重要,因为两者都会干扰applicationHost.config,并且都可以用来实现相同的结果。您试图实现的是什么?我试图以编程方式创建应用程序,将其链接到特定的应用程序池,然后将windows auth更改为true,anon auth更改为false