Как я могу объединить этот повторяющийся код C#? - PullRequest
0 голосов
/ 08 апреля 2020

По сути, моя программа выполняет удаленное взаимодействие с сервером, останавливает пул приложений в IIS, копирует файл и, наконец, перезапускает пул приложений. Я должен применить эту же процедуру к шести различным серверам. Как я могу объединить это в самый простой и эффективный код?

Вот мой код прямо сейчас (в основном он делает то же самое, 6 раз):

using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer1"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer1\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}



using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer2"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer2\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}



using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer3"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer3\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}



using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer4"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer4\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}



using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer5"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer5\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}



using (ServerManager mgr = ServerManager.OpenRemote("RemoteServer6"))
{
    ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
    if (appPool != null)
    {
        if (appPool.State == ObjectState.Started)
        {
            appPool.Stop();
        }
    }

    File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @"\\RemoteServer6\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
}

Ответы [ 2 ]

0 голосов
/ 08 апреля 2020

Извлеките одно из этих изменений в метод, заменив изменения в параметрах:

public void CopyToRemote(string remoteServer)
{
    using (ServerManager mgr = ServerManager.OpenRemote(remoteServer))
    {
        ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
        if (appPool != null)
        {
            if (appPool.State == ObjectState.Started)
            {
                appPool.Stop();
            }
        }

        File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", string.Format(@"\\{0}\Users\TestUser\Documents\testfile.txt", remoteServer));
        appPool.Start;
    }
}

Вызов, как:

for (int index = 1; index <= 6; index++)
{
    CopyToRemote($"RemoteServer{index}");
}
0 голосов
/ 08 апреля 2020

Поместите все в метод, который принимает имя сервера в качестве параметра

public void CopyFileToServer(string targetServerName)
{
    using (ServerManager mgr = ServerManager.OpenRemote(targetServerName)) 
    {
        ApplicationPool appPool = mgr.ApplicationPools["TestAppPool"];
        if (appPool != null)
        {
            if (appPool.State == ObjectState.Started)
            {
                appPool.Stop();
            }
        }

        // Depending on the Framework or Core version you might need to play
        // with the string interpolation for the second parameter
        File.Copy(@"C:\Users\TestUser\Downloads\testfile.txt", @$"\\{targetServerName}\Users\TestUser\Documents\testfile.txt");
    appPool.Start;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...