RDP to ip address from onclick menuItem #c VS - c#

I'm trying to launch a remote desktop session to a specified IP on an onClick function on a menuItem in VS.
private void NAMEHEREToolStripMenuItem_Click(object sender, EventArgs e)
{
// launch remote desktop to 192.168.0.1
}
So I click NAMEHERE and it should open remote desktop and automatically connect to the IP I've given it. How can I do this? I've googled different things but cant quite find what I want.
Thanks!

On Windows you can launch the remote desktop program with the /v argument, like this:
mstsc.exe /v 192.168.0.1
you can also define a port after the IP if needed: 192.168.0.1:1234 for example.
For all arguments, launch it in command propmt:
mstsc.exe -?

and to start the process:
// launch remote desktop to 192.168.0.1
var ipAddress = "192.168.0.1";
var pinfo = new System.Diagnostics.ProcessStartInfo("mstsc.exe");
pinfo.Arguments = "/v " + ipAddress;
Process.Start(pinfo);

Related

Auto Detect The Application on LAN using C#.net

I have an Open Source Voice Chatting application which works fine on LAN.
But the problem is with connecting two PCs Manually.
Let's suppose there are two PCs (Application instances), PC A and PC B.
To make a connection I have to put the IP Address of the PC A into PC B and IP Address of the PC B into PC A.
I want to make the small code change where if the application is running on two PCs and they both are connected via LAN then both sides get the IP address automatically. Like auto-detection.
So my logic was to first know the IP Address on the LAN using arp -a command then writes the output in a text file and only obtain the IP addresses that start with 192... and check the instance of the application on each address using This Solution.
Unfortunately, I end up getting an error which states that.
Unhandled Exception: System.Runtime.InteropServices.COMException: The
RPC server is unavailable.
at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo) at
System.Management.ManagementScope.InitializeGuts(Object o) at
System.Management.ManagementScope.Initialize() at
System.Management.ManagementObjectSearcher.Initialize() at
System.Management.ManagementObjectSearcher.Get()
This is the code which i used to accomplish this task.
//Write the cmd Output in a text file
string strCmdText;
strCmdText = #"/K arp -a > C:\Test\Result.txt";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
//To get the IP address which starts with the 192.
const string ipPattern = #"^\s*(192\.168\.\d{1,3}\.\d{1,3}\b)";
var ipRegex = new Regex(ipPattern);
var ipAddresses192168 = File.ReadAllLines(#"C:\Test\Result.txt")
.Skip(3) // Skip 3 lines
.Where(line => ipRegex.IsMatch(line))
.Select(line => ipRegex.Match(line).Groups[1].Value);
foreach (var ipAddress in ipAddresses192168)
{
Console.WriteLine(ipAddress);
// Check for the running instance of the application on LAN network.
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2");
string query = "SELECT * FROM Win32_Process WHERE Name='WavPlayer.exe'";
var searcher = new ManagementObjectSearcher(query);
searcher.Scope = scope;
bool isRunning = searcher.Get().Count > 0;
}
So my question is, Is there any other straight forward process to accomplish this task using C#.net?
I am available to provide more info about this question so any help is appreciated.

adding a user input into c# process

So im trying to make a ip pinger to see if a server is online and have got this so far i would like it so that the user can in put a ip on there own from a text box. but keep getting a error on the start part.
Error CS1501 No overload for method 'Start' takes 3 arguments
System.Diagnostics.Process.Start ("cmd", "/k ping" + flatTextBox1.Text ,"-t");
I see several issues here:
First, the "-t" is used as third parameter because of the comma before it. You should add it to the string you're building with "/k" in combination with the IP address.
Next, given the textbox text is "127.0.0.1" this will currently end up as: /k ping127.0.0.1
So you might just add a space in between the "ping" and the IP.
BUT: you should not use cmd.exe for this, consider to use the Ping class from the .NET framework.
Try using ProcessStartInfo:
ProcessStartInfo startInfo = new ProcessStartInfo("cmd");
startInfo.Arguments = "/k ping " + flatTextBox1.Text + " -t";
Process.Start(startInfo);

Getting al ip's

So, i'm new to C# and visual studio and stuff. But i searched arround for how to get all ip's, Like you see in the Windows Firewall app. But I can't find any thing to get started with. I saw alot of posts about Dns, And stuff So i got this:
private void ip()
{
StringBuilder sb = new StringBuilder();
// Get host name
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Enumerate IP addresses
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
sb.AppendLine(strHostName + " - " + ipaddress);
label1.Text = sb.ToString().Replace(Environment.NewLine, "\n");
}
}
But I only get 4 ip's but i want all ip's currently connecting to my pc.
(And an i know there are alot of posts about this, but i'm searching for an answer for an beginning programmer to understand)
Could anybody help me?
Thanks!
That code you show gets the IPs assigned to the current machine.
What it sounds like you want is the equivalent of running netstat on the command line (get all active connections). This question should get you started: How to determine tcp port used by Windows process in C#
Basically you use GetActiveTcpConnections.

Check if a port is assigned to any program or added in firewall - C#

We have Windows Service which will be installed by installer. We have an option to allow user to provide a port number and select whether the service must start on completion of installation. We are having a check on installer itself for checking whether the port is open/available.
TcpClient TcpScan = new TcpClient();
TcpScan.Connect("localhost", portno);
if (TcpScan.Connected == true)
{
TcpScan.Close();
}
My problem is if the user selects the option of not to start the service on installation and then we install another instance on the same machine with the same port as used in first one, then if we start both the services then one of the service will not work.
So is there any way I can check whether the port provided by user is already there in firewall or is already assigned to some other windows service? (Also assume the service can be in stopped state)
I think no, because any app could open a port at runtime.
You can (for example) use a Mutex to avoid multiple instances of your service on the same port (giving the mutex a name like String.Format(MyMutex_{0},my_port}.
And you could/should check if that port is free during service startup and close it gracefully if it's not.
Finally got the answer by doing some R&D
string OP = #"C:\Windows\Temp\ExceptionList.txt";
ProcessStartInfo procStartInfo = null;
string command = "netsh advfirewall firewall show rule name=all > " + OP;
procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
if (File.Exists(OP))
{
StreamReader SR = new StreamReader(OP);
string FileData = SR.ReadToEnd();
SR.Close();
//Logic to read the output and then fetch only records which are enabled and have LocalPort
}
Output (ExceptionList.txt) file contains data in this format
Rule Name: NETTCP
---------------------------------------------
Enabled: Yes
Direction: In
Profiles: Domain
Grouping:
LocalIP: Any
RemoteIP: Any
Protocol: TCP
LocalPort: 8080
RemotePort: Any
Edge traversal: No
Action: Allow

How to execute process on remote machine, in C#

How can I start a process on a remote computer in c#, say computer name = "someComputer", using System.Diagnostics.Process class?
I created a small console app on that remote computer that just writes "Hello world" to a txt file, and I would like to call it remotely.
Console app path: c:\MyAppFolder\MyApp.exe
Currently I have this:
ProcessStartInfo startInfo = new ProcessStartInfo(string.Format(#"\\{0}\{1}", someComputer, somePath);
startInfo.UserName = "MyUserName";
SecureString sec = new SecureString();
string pwd = "MyPassword";
foreach (char item in pwd)
{
sec.AppendChar(item);
}
sec.MakeReadOnly();
startInfo.Password = sec;
startInfo.UseShellExecute = false;
Process.Start(startInfo);
I keep getting "Network path was not found".
Can can use PsExec from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
Or WMI:
object theProcessToRun() = { "YourFileHere" };
ManagementClass theClass = new ManagementClass(#"\\server\root\cimv2:Win32_Process");
theClass.InvokeMethod("Create", theProcessToRun);
Use one of the following:
(EDIT) Remote Powershell
WMI (see Ivan G's answer)
Task Scheduler API (http://msdn.microsoft.com/en-us/library/windows/desktop/aa383606%28v=vs.85%29.aspx)
PsExec
WshRemote object with a dummy script. Chances are, it works via DCOM, activating some of scripting objects remotely.
Or if you feel like it, inject your own service or COM component. That would be very close to what PsExec does.
Of all these methods, I prefer task scheduler. The cleanest API of them all, I think. Connect to the remote task scheduler, create a new task for the executable, run it. Note: the executable name should be local to that machine. Not \servername\path\file.exe, but c:\path\file.exe. Delete the task if you feel like it.
All those methods require that you have administrative access to the target machine.
ProcessStartInfo is not capable of launching remote processes.
According to MSDN, a Process object only allows access to remote processes not the ability to start or stop remote processes. So to answer your question with respect to using this class, you can't.
An example with WMI and other credentials as the current process, on default it used the same user as the process runs.
var hostname = "server"; //hostname or a IpAddress
var connection = new ConnectionOptions();
//The '.\' is for a local user on the remote machine
//Or 'mydomain\user' for a domain user
connection.Username = #".\Administrator";
connection.Password = "passwordOfAdministrator";
object[] theProcessToRun = { "YourFileHere" }; //for example notepad.exe
var wmiScope = new ManagementScope($#"\\{hostname}\root\cimv2", connection);
wmiScope.Connect();
using (var managementClass = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
managementClass.InvokeMethod("Create", theProcessToRun);
}
I don't believe you can start a process through a UNC path directly; that is, if System.Process uses the windows comspec to launch the application... how about you test this theory by mapping a drive to "\someComputer\somePath", then changing your creation of the ProcessStartInfo to that? If it works that way, then you may want to consider temporarily mapping a drive programmatically, launch your app, then remove the mapping (much like pushd/popd works from a command window).

Categories

Resources