Sunday, August 8, 2010

C# FAQs Series: Get Names of All Machine on LAN


In C# FAQs Series: We discuss most frequent questions asked on C# forums.
In this session we will see how to get all machines connected on LAN using C# code. 
You can use windows built-in tool net.exe to achieve this. All you need to do is start it using Process  class and send view command.
 
using System.Diagnostics; 
using System.IO; 
    //Gets the machine names that are connected on LAN 
 Process NetworkUtility = new Process(); 
 NetworkUtility.StartInfo.FileName = "net.exe"; 
NetworkUtility.StartInfo.CreateNoWindow = true; 
 NetworkUtility.StartInfo.Arguments = "view"; 
 NetworkUtility.StartInfo.RedirectStandardOutput = true; 
 NetworkUtility.StartInfo.UseShellExecute = false; 
 NetworkUtility.StartInfo.RedirectStandardError = true; 
 NetworkUtility.Start(); 
 StreamReader streamReader = new StreamReader(NetworkUtility.StandardOutput.BaseStream,  NetworkUtility.StandardOutput.CurrentEncoding); 
string line = ""; 
while ((line = streamReader.ReadLine()) != null) 
 { 
      if (line.StartsWith("\\")) 
      {             listBox1.Items.Add(line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ")).ToUpper()); 
      } 
} 
 streamReader.Close(); 
NetworkUtility.WaitForExit(1000); 
All machines on LAN will be added in listBox1.