SoFunction
Updated on 2025-03-07

C# console program implements code sharing to enable and close SQLServer services


using System;
using ;
using ;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            while (1 == 1)
            {
('\n\n Optional operation: \n\n 1. Start the database service 2. Stop the database service \n\n Start execution : ');
                string strQueryState = ();
                if (() == '1')
                {
                    string strFilePath = GetFilePath('Start');
                    (strFilePath, GetCmdStr('start'), ('gb2312'));
                    (strFilePath);
                }
                else if (() == '2')
                {
                    string strFilePath = GetFilePath('Stop');
                    (strFilePath, GetCmdStr('stop'), ('gb2312'));
                    (strFilePath);
                }
            }

        }

        /// <summary>
/// Cmd instruction required for operation
        /// </summary>
/// <param name='StateStr'>Operation</param>
/// <returns>Cmd directive</returns>
        private static string GetCmdStr(string StateStr)
        {
            string cmdStr = '';
            if (().Trim() == 'start')
            {
cmdStr = @'@echo. & del %0 & @echo off & @echo.Starting the service MSSQLSERVER and MSSQLSERVERAGENT ...... & '
+ '@echo. & @net start MSSQLSERVER & @net start SQLSERVERAGENT & @echo. The service is started!';
            }
            else if (().Trim() == 'stop')
            {
cmdStr = @'@echo. & del %0 & @echo off & @echo.Stop service MSSQLSERVER and MSSQLSERVERAGENT ...... & '
+ '@echo. & @net stop sqlserveragent &  @net stop mssqlserver & @echo.Service stopped!';
            }
            return cmdStr;
        }

        /// <summary>
/// Get whether a file exists on disk
        /// </summary>
/// <param name='PathStr'>File name</param>
/// <returns>Return to create file path</returns>
        private static string GetFilePath(string strFileName)
        {
string strTem = '';// Used to store the file path to be saved
string[] strPath = new string[] {@'C:\\',@'D:\\',@'E:\\',@'F:\\'};//Detected drive letter
            strFileName += () + () + ()
+ () + () + () + ().Trim()+'.cmd';//To prevent duplicate rename of files

foreach (string pathStr in strPath)//Cycle to determine the existence of the file directory
            {
if (!(pathStr))//Judge the directory exists
                {
                    continue;
                }
                else
                {
if ((pathStr + strFileName))//Judge the existence of the file
                    {
                        continue;
                    }
                    else
                    {
                        strTem = pathStr + strFileName;
                        break;
                    }
                }
            }
return strTem;//Return the path to buildable file
        }
    }
}