我如何控制Mysql服务器存在于使用C#命令的服务中?
如果Mysql服务器的“displayname”和“servicename”不是使用C#命令的“Mysql”,我如何控制Mysql服务器存在于服务中 如果“displayname”和“servicename”是“MySql”,我可以使用“ServiceController.GetServices();”进行控制,但当我更改名称时,我无法控制该MySql服务器是否存在于服务中或安装在我的计算机中 如何使用C#命令控制计算机中的mysql服务器 MyCode我如何控制Mysql服务器存在于使用C#命令的服务中?,c#,mysql,service,C#,Mysql,Service,如果Mysql服务器的“displayname”和“servicename”不是使用C#命令的“Mysql”,我如何控制Mysql服务器存在于服务中 如果“displayname”和“servicename”是“MySql”,我可以使用“ServiceController.GetServices();”进行控制,但当我更改名称时,我无法控制该MySql服务器是否存在于服务中或安装在我的计算机中 如何使用C#命令控制计算机中的mysql服务器 MyCode private void For
private void Form1_Load(object sender, EventArgs e)
{
bool sonuc = serviceExists("mysql");
if(sonuc==true)
{
MessageBox.Show("MySQL Exists.");
}
else
{
MessageBox.Show("MySQL doesnt exist.");
}
}
public bool serviceExists(string ServiceName)
{
return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(ServiceName));
}
其实很容易,
首先,通过简单地询问windows使用名称空间系统中的进程来查看现有进程
Process[] ProcessList = Process.GetProcesses()
var started= ProcessList.Any(a => a.ProcessName.Equals("mysql", StringComparison.OrdinalIgnoreCase));
但问题是,MySql使用的是什么名称,是默认名称还是另一个名称,那么问题是它们有多少个
也许,您可以选择查看端口,并查看给定网络端口上正在侦听的应用程序,因为这样更可靠,因为端口可能会为您提供有关所面临安装的更多信息
所以,我要做的是获取所有网卡的所有IP句柄,看看谁在和谁说话。
我的代码
这将返回具有以下签名的类:
public class TcpProcessRecord
{
[DisplayName("Local Address")]
public IPAddress LocalAddress { get; set; }
[DisplayName("Local Port")]
public ushort LocalPort { get; set; }
[DisplayName("Remote Address")]
public IPAddress RemoteAddress { get; set; }
[DisplayName("Remote Port")]
public ushort RemotePort { get; set; }
[DisplayName("State")]
public MibTcpState State { get; set; }
[DisplayName("Process ID")]
public int ProcessId { get; set; }
[DisplayName("Process Name")]
public string ProcessName { get; set; }
}
当您匹配process.GetProcesses()返回的进程ID时
您知道哪个应用程序有网络连接,它在哪个端口上尝试连接
这也可以方便地查看您的服务是否不可用,因为您的防火墙正在阻止给定的端口。
神奇之处在于我发现了一些代码,由于原始代码的某些方法被.NET4.7.X弃用,我不得不对其进行一些更新
我不确定我在哪里找到了原始代码,但这是我的版本
public class TCP
{
#region TCP
private const int AF_INET = 2;
// The GetExtendedTcpTable function retrieves a table that contains a list of
// TCP endpoints available to the application. Decorating the function with
// DllImport attribute indicates that the attributed method is exposed by an
// unmanaged dynamic-link library 'iphlpapi.dll' as a static entry point.
[DllImport("iphlpapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int pdwSize, bool bOrder, int ulAf, TcpTableClass tableClass, uint reserved = 0);
/// <summary>
/// This function reads and parses the active TCP socket connections available
/// and stores them in a list.
/// </summary>
/// <returns>
/// It returns the current set of TCP socket connections which are active.
/// </returns>
/// <exception cref="OutOfMemoryException">
/// This exception may be thrown by the function Marshal.AllocHGlobal when there
/// is insufficient memory to satisfy the request.
/// </exception>
public List<TcpProcessRecord> GetAllTcpConnections()
{
int bufferSize = 0;
List<TcpProcessRecord> tcpTableRecords = new List<TcpProcessRecord>();
// Getting the size of TCP table, that is returned in 'bufferSize' variable.
uint result = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
// Allocating memory from the unmanaged memory of the process by using the
// specified number of bytes in 'bufferSize' variable.
IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);
try
{
// The size of the table returned in 'bufferSize' variable in previous
// call must be used in this subsequent call to 'GetExtendedTcpTable'
// function in order to successfully retrieve the table.
result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
// Non-zero value represent the function 'GetExtendedTcpTable' failed,
// hence empty list is returned to the caller function.
if (result != 0)
return new List<TcpProcessRecord>();
// Marshals data from an unmanaged block of memory to a newly allocated
// managed object 'tcpRecordsTable' of type 'MIB_TCPTABLE_OWNER_PID'
// to get number of entries of the specified TCP table structure.
MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));
IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));
// Reading and parsing the TCP records one by one from the table and
// storing them in a list of 'TcpProcessRecord' structure type objects.
for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
{
MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
tcpTableRecords.Add(new TcpProcessRecord(
new IPAddress(tcpRow.localAddr),
new IPAddress(tcpRow.remoteAddr),
BitConverter.ToUInt16(new byte[2] {
tcpRow.localPort[1],
tcpRow.localPort[0] }, 0),
BitConverter.ToUInt16(new byte[2] {
tcpRow.remotePort[1],
tcpRow.remotePort[0] }, 0),
tcpRow.owningPid, tcpRow.state));
tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
}
}
finally
{
Marshal.FreeHGlobal(tcpTableRecordsPtr);
}
return tcpTableRecords != null ? tcpTableRecords.Distinct().ToList<TcpProcessRecord>() : new List<TcpProcessRecord>();
}
enum TcpTableClass
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
// Enum for different possible states of TCP connection
public enum MibTcpState
{
CLOSED = 1,
LISTENING = 2,
SYN_SENT = 3,
SYN_RCVD = 4,
ESTABLISHED = 5,
FIN_WAIT1 = 6,
FIN_WAIT2 = 7,
CLOSE_WAIT = 8,
CLOSING = 9,
LAST_ACK = 10,
TIME_WAIT = 11,
DELETE_TCB = 12,
NONE = 0
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public MibTcpState state;
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint remoteAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public int owningPid;
}
/// <summary>
/// The structure contains a table of process IDs (PIDs) and the IPv4 TCP links that
/// are context bound to these PIDs.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
// [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStruct, SizeConst = 1)]
public MIB_TCPROW_OWNER_PID[] table;
}
/// <summary>
/// This class provides access an IPv4 TCP connection addresses and ports and its
/// associated Process IDs and names.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class TcpProcessRecord
{
[DisplayName("Local Address")]
public IPAddress LocalAddress { get; set; }
[DisplayName("Local Port")]
public ushort LocalPort { get; set; }
[DisplayName("Remote Address")]
public IPAddress RemoteAddress { get; set; }
[DisplayName("Remote Port")]
public ushort RemotePort { get; set; }
[DisplayName("State")]
public MibTcpState State { get; set; }
[DisplayName("Process ID")]
public int ProcessId { get; set; }
[DisplayName("Process Name")]
public string ProcessName { get; set; }
public TcpProcessRecord(IPAddress localIp, IPAddress remoteIp, ushort localPort,
ushort remotePort, int pId, MibTcpState state)
{
LocalAddress = localIp;
RemoteAddress = remoteIp;
LocalPort = localPort;
RemotePort = remotePort;
State = state;
ProcessId = pId;
// Getting the process name associated with a process id.
if (Process.GetProcesses().Any(process => process.Id == pId))
{
ProcessName = Process.GetProcessById(ProcessId).ProcessName;
}
}
}
/// <summary>
/// The structure contains an entry from the User Datagram Protocol (UDP) listener
/// table for IPv4 on the local computer. The entry also includes the process ID
/// (PID) that issued the call to the bind function for the UDP endpoint.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public int owningPid;
}
#endregion
}
公共类TCP
{
#区域TCP
私有常量int AF_INET=2;
//GetExtendedTcpTable函数检索一个包含
//TCP端点可用于应用程序。使用
//DllImport属性表示属性化方法由
//作为静态入口点的非托管动态链接库“iphlapi.dll”。
[DllImport(“iphlapi.dll”,CharSet=CharSet.Auto,SetLastError=true)]
私有静态外部uint GetExtendedTcpTable(IntPtr pTcpTable,ref int pdwSize,bool bOrder,int ulAf,TcpTableClass tableClass,uint reserved=0);
///
///此函数用于读取和解析可用的活动TCP套接字连接
///并将其存储在列表中。
///
///
///它返回当前活动的TCP套接字连接集。
///
///
///出现此异常时,函数Marshal.AllocHGlobal可能会引发此异常
///内存不足,无法满足请求。
///
公共列表GetAllTcpConnections()
{
int bufferSize=0;
List tcpTableRecords=新列表();
//获取“bufferSize”变量中返回的TCP表的大小。
uint result=GetExtendedTcpTable(IntPtr.Zero,ref bufferSize,true,AF\u INET,TcpTableClass.TCP\u TABLE\u OWNER\u PID\u ALL);
//使用从进程的非托管内存分配内存
//“bufferSize”变量中指定的字节数。
IntPtr tcpTableRecordsPtr=Marshal.AllocHGlobal(bufferSize);
尝试
{
//在上一页的“bufferSize”变量中返回的表的大小
//此调用必须在对“GetExtendedTcpTable”的后续调用中使用
//函数以成功检索表。
结果=GetExtendedTcpTable(tcpTableRecordsPtr,ref bufferSize,true,AF\u INET,TcpTableClass.TCP\u TABLE\u OWNER\u PID\u ALL);
//非零值表示函数“GetExtendedTcpTable”失败,
//因此,空列表将返回给调用方函数。
如果(结果!=0)
返回新列表();
//将数据从非托管内存块封送到新分配的
//类型为“MIB\u TCPTABLE\u OWNER\u PID”的托管对象“tcpRecordsTable”
//获取指定TCP表结构的条目数。
MIB_TCPTABLE_OWNER_PID tcpRecordsTable=(MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr,typeof(MIB_TCPTABLE_OWNER_PID));
IntPtr tableRowPtr=(IntPtr)((长)tcpTableRecordsPtr+marshall.SizeOf(tcpRecordsTable.dwNumEntries));
//从表中逐个读取和解析TCP记录,然后
//将它们存储在“TcpProcessRecord”结构类型对象列表中。
for(int row=0;rowpublic class TCP
{
#region TCP
private const int AF_INET = 2;
// The GetExtendedTcpTable function retrieves a table that contains a list of
// TCP endpoints available to the application. Decorating the function with
// DllImport attribute indicates that the attributed method is exposed by an
// unmanaged dynamic-link library 'iphlpapi.dll' as a static entry point.
[DllImport("iphlpapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int pdwSize, bool bOrder, int ulAf, TcpTableClass tableClass, uint reserved = 0);
/// <summary>
/// This function reads and parses the active TCP socket connections available
/// and stores them in a list.
/// </summary>
/// <returns>
/// It returns the current set of TCP socket connections which are active.
/// </returns>
/// <exception cref="OutOfMemoryException">
/// This exception may be thrown by the function Marshal.AllocHGlobal when there
/// is insufficient memory to satisfy the request.
/// </exception>
public List<TcpProcessRecord> GetAllTcpConnections()
{
int bufferSize = 0;
List<TcpProcessRecord> tcpTableRecords = new List<TcpProcessRecord>();
// Getting the size of TCP table, that is returned in 'bufferSize' variable.
uint result = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
// Allocating memory from the unmanaged memory of the process by using the
// specified number of bytes in 'bufferSize' variable.
IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);
try
{
// The size of the table returned in 'bufferSize' variable in previous
// call must be used in this subsequent call to 'GetExtendedTcpTable'
// function in order to successfully retrieve the table.
result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
// Non-zero value represent the function 'GetExtendedTcpTable' failed,
// hence empty list is returned to the caller function.
if (result != 0)
return new List<TcpProcessRecord>();
// Marshals data from an unmanaged block of memory to a newly allocated
// managed object 'tcpRecordsTable' of type 'MIB_TCPTABLE_OWNER_PID'
// to get number of entries of the specified TCP table structure.
MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));
IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));
// Reading and parsing the TCP records one by one from the table and
// storing them in a list of 'TcpProcessRecord' structure type objects.
for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
{
MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
tcpTableRecords.Add(new TcpProcessRecord(
new IPAddress(tcpRow.localAddr),
new IPAddress(tcpRow.remoteAddr),
BitConverter.ToUInt16(new byte[2] {
tcpRow.localPort[1],
tcpRow.localPort[0] }, 0),
BitConverter.ToUInt16(new byte[2] {
tcpRow.remotePort[1],
tcpRow.remotePort[0] }, 0),
tcpRow.owningPid, tcpRow.state));
tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
}
}
finally
{
Marshal.FreeHGlobal(tcpTableRecordsPtr);
}
return tcpTableRecords != null ? tcpTableRecords.Distinct().ToList<TcpProcessRecord>() : new List<TcpProcessRecord>();
}
enum TcpTableClass
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
// Enum for different possible states of TCP connection
public enum MibTcpState
{
CLOSED = 1,
LISTENING = 2,
SYN_SENT = 3,
SYN_RCVD = 4,
ESTABLISHED = 5,
FIN_WAIT1 = 6,
FIN_WAIT2 = 7,
CLOSE_WAIT = 8,
CLOSING = 9,
LAST_ACK = 10,
TIME_WAIT = 11,
DELETE_TCB = 12,
NONE = 0
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public MibTcpState state;
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint remoteAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public int owningPid;
}
/// <summary>
/// The structure contains a table of process IDs (PIDs) and the IPv4 TCP links that
/// are context bound to these PIDs.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
// [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStruct, SizeConst = 1)]
public MIB_TCPROW_OWNER_PID[] table;
}
/// <summary>
/// This class provides access an IPv4 TCP connection addresses and ports and its
/// associated Process IDs and names.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class TcpProcessRecord
{
[DisplayName("Local Address")]
public IPAddress LocalAddress { get; set; }
[DisplayName("Local Port")]
public ushort LocalPort { get; set; }
[DisplayName("Remote Address")]
public IPAddress RemoteAddress { get; set; }
[DisplayName("Remote Port")]
public ushort RemotePort { get; set; }
[DisplayName("State")]
public MibTcpState State { get; set; }
[DisplayName("Process ID")]
public int ProcessId { get; set; }
[DisplayName("Process Name")]
public string ProcessName { get; set; }
public TcpProcessRecord(IPAddress localIp, IPAddress remoteIp, ushort localPort,
ushort remotePort, int pId, MibTcpState state)
{
LocalAddress = localIp;
RemoteAddress = remoteIp;
LocalPort = localPort;
RemotePort = remotePort;
State = state;
ProcessId = pId;
// Getting the process name associated with a process id.
if (Process.GetProcesses().Any(process => process.Id == pId))
{
ProcessName = Process.GetProcessById(ProcessId).ProcessName;
}
}
}
/// <summary>
/// The structure contains an entry from the User Datagram Protocol (UDP) listener
/// table for IPv4 on the local computer. The entry also includes the process ID
/// (PID) that issued the call to the bind function for the UDP endpoint.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public int owningPid;
}
#endregion
}