以编程方式启用IIS角色和功能

时间:2015-05-25 06:36:40

标签: c# iis dism

我正在尝试通过c#console应用程序启用IIS功能。它在Windows 7和Windows 8.1机器上运行良好。但是当我在Windows Server 2008 R2和Windows Server 2012 R2上运行相同的代码时,它无法正常工作。我在这段代码中缺少什么?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text.RegularExpressions;

namespace EnableIISComponents
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SetupIIS();
                Console.WriteLine("Done. Press any key to close.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred:" + ex.Message);
            }
            Console.ReadLine();
        }
    static string SetupIIS()
    {
        // In command prompt run this command to see all the features names which are equivalent to UI features.
        // c:\>dism /online /get-features /format:table 
        var featureNames = new List<string> 
                {
                    "IIS-ApplicationDevelopment",                        
                    "IIS-ISAPIExtensions",
                    "IIS-ISAPIFilter",
                    "IIS-CommonHttpFeatures",
                    "IIS-DefaultDocument",
                    "IIS-HttpErrors",
                    "IIS-StaticContent",
                    "IIS-HealthAndDiagnostics",
                    "IIS-HttpLogging",
                    "IIS-HttpTracing",
                    "IIS-WebServer",
                    "IIS-WebServerRole",
                    "IIS-ManagementConsole",
                };

        Console.WriteLine("Checking the Operating System...\n");

        ManagementObjectSearcher obj = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
        try
        {
            foreach (ManagementObject wmi in obj.Get())
            {
                string Name = wmi.GetPropertyValue("Caption").ToString();

                // Remove all non-alphanumeric characters so that only letters, numbers, and spaces are left.
                // Imp. for 32 bit window server 2008
                Name = Regex.Replace(Name.ToString(), "[^A-Za-z0-9 ]", "");

                if (Name.Contains("Server 2012 R2") || Name.Contains("Windows 81"))
                {
                    featureNames.Add("IIS-ASPNET45");
                    featureNames.Add("IIS-NetFxExtensibility45");
                }
                else if (Name.Contains("Server 2008 R2") || Name.Contains("Windows 7"))
                {
                    featureNames.Add("IIS-ASPNET");
                    featureNames.Add("IIS-NetFxExtensibility");
                }
                else
                {
                    featureNames.Clear();
                }

                string Version = (string)wmi["Version"];
                string Architecture = (string)wmi["OSArchitecture"];

                Console.WriteLine("Operating System details:");
                Console.WriteLine("OS Name: " + Name);
                Console.WriteLine("Version: " + Version);
                Console.WriteLine("Architecture: " + Architecture + "\n");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred:" + ex.Message);
        }

        return Run(
            "dism",
            string.Format(
                "/NoRestart /Online /Enable-Feature {0}",
                string.Join(
                    " ",
                    featureNames.Select(name => string.Format("/FeatureName:{0}", name)))));
    }

    static string Run(string fileName, string arguments)
    {
        Console.WriteLine("Enabling IIS features...");
        Console.WriteLine(arguments);

        using (var process = Process.Start(new ProcessStartInfo
        {
            FileName = fileName,
            Arguments = arguments,
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardOutput = true,
            UseShellExecute = false,
        }))
        {
            process.WaitForExit();
            return process.StandardOutput.ReadToEnd();
        }
    }

}
}

而不是在服务器计算机上运行此程序如果我通过命令提示符运行具有相同feaureNames的dism命令,则IIS功能将启用。为什么不与该计划合作?

我正在以管理员身份运行我的程序,方法是右键单击并选择“以管理员身份运行”。

我已经通过此链接创建了此示例。 Better way to install IIS7 programmatically

1 个答案:

答案 0 :(得分:0)

最后我找到了原因。 在项目属性中,目标平台是“任何CPU” 但检查了“首选32位”选项。这导致了问题。 在服务器2012 R2我的应用程序尝试使用32位版本的DISM。这导致了问题。

一旦我取消选中该选项。它工作正常。