Friday, October 23, 2009

Getting all machines in LAN using VB.NET

Drag one list box and name it as LBox
In form load write the below code

Dim childEntry As DirectoryEntry
Dim ParentEntry As New DirectoryEntry
Try
ParentEntry.Path = "WinNT:"
For Each childEntry In ParentEntry.Children
Select Case childEntry.SchemaClassName
Case "Domain"

Dim SubChildEntry As DirectoryEntry
Dim SubParentEntry As New DirectoryEntry
SubParentEntry.Path = "WinNT://" & childEntry.Name
For Each SubChildEntry In SubParentEntry.Children

Select Case SubChildEntry.SchemaClassName
Case "Computer"
LBox.Items.Add(SubChildEntry.Name)
End Select
Next
End Select
Next
Catch Excep As Exception
MsgBox("Error While Reading Directories")
Finally
ParentEntry = Nothing
End Try


On listbox changed write the below code to get the ip address

Try
Dim IPHEntry As Net.IPHostEntry
Dim IPAdd() As Net.IPAddress

Dim localHost As String
localHost = Dns.GetHostName()
IPHEntry = Dns.GetHostByName(LBox.SelectedItem.ToString())
IPAdd = IPHEntry.AddressList
Dim i As Integer

For i = 0 To IPAdd.GetUpperBound(0)

'Console.Write("IP Address {0}: {1} ", i, IPAdd(i).ToString)
MessageBox.Show(IPAdd(i).ToString)
'txtIp.Text = IPAdd(i).ToString
Next


Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Function to export DataTable to csv File

public void CreateCSVFile(DataTable dt, string strFilePath)
{
try
{
// Create the CSV file to which grid data will be exported.

StreamWriter sw = new StreamWriter(strFilePath, false);

int iColCount = dt.Columns.Count;

foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount-2; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}

if (i < iColCount - 1)
{
sw.Write(",");
}

}

sw.Write(sw.NewLine);

}
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}