WinNT giving to much information. I need to narrow down to just Machine Names - vb.net

Dim de As New System.DirectoryServices.DirectoryEntry()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
de.Path = "WinNT://*****".Replace("*****", ActiveDirectory.Domain.GetCurrentDomain.Name)
Dim Mystream As Object
MsgBox("Please choose the place you want the file")
If savefileDialog1.ShowDialog() = DialogResult.OK Then Mystream = savefileDialog1.FileName
Dim UserFile As String = savefileDialog1.FileName & ".txt"
Dim fileExists As Boolean = File.Exists(UserFile)
Using sw As New StreamWriter(File.Open(UserFile, FileMode.OpenOrCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Using
End Sub
I am getting a large number of entries written out to the text file. The bottom half of the file is all that I really need. The bottom half seems to be the list of all machine names on the domain and the first half is filled with names or printers, and other names that i cannot "pushd \" into.
I am unable to figure out what will cut down this user list and give me only the machine names.

You might find something here...look at "Enumerate Objects in an OU"
Public Function EnumerateOU(OuDn As String) As ArrayList
Dim alObjects As New ArrayList()
Try
Dim directoryObject As New DirectoryEntry("LDAP://" + OuDn)
For Each child As DirectoryEntry In directoryObject.Children
Dim childPath As String = child.Path.ToString()
alObjects.Add(childPath.Remove(0, 7))
'remove the LDAP prefix from the path
child.Close()
child.Dispose()
Next
directoryObject.Close()
directoryObject.Dispose()
Catch e As DirectoryServicesCOMException
Console.WriteLine("An Error Occurred: " + e.Message.ToString())
End Try
Return alObjects
End Function

I'm not sure if there is much difference in our active directory setups, but I ran the following code in a console application and it only output the AD Names (as expected):
Module Module1
Sub Main()
Using de As New System.DirectoryServices.DirectoryEntry
de.Path = "WinNT://*****".Replace("*****", System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.Name)
For Each d As System.DirectoryServices.DirectoryEntry In de.Children()
If d.SchemaEntry.Name = "User" Then
Console.WriteLine(d.Name)
End If
Next
Console.ReadKey()
End Using
End Sub
End Module
EDIT:
Code change to only output members with the SchemaType of "User"

Related

Importing data from text file in VB.NET

So, I am trying to develop a book database. I have created a table with 11 columns which populates a DGV, where only 6 columns are showed. The full data of each book is shown in a lower part of the form, where I have textboxes, which are bounded (BindingSource) to the table, that change as I move in the DGV.
Now, what I want to do is to have the posibility to export/import data from a file.
I have accomplished the exporting part with the following code:
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
Dim txt As String = String.Empty
For Each row As DataGridViewRow In DbdocsDataGridView.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
txt += CStr(cell.Value & ","c)
Next
'Add new line.
txt += vbCr & vbLf
Next
Dim folderPath As String = "C:\CSV\"
File.WriteAllText(folderPath & "DataGridViewExport.txt", txt)
End Sub
However, I can't manage to import from the txt. What I've tried is this: https://1bestcsharp.blogspot.com/2018/04/vb.net-import-txt-file-text-to-datagridview.html
It works perfectly if you code the table and it populates de DGV without problem. I can't see how should I adapt that code to my need.
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
DbdocsDataGridView.DataSource = table
Dim filas() As String
Dim valores() As String
filas = File.ReadAllLines("C:\CSV\DataGridViewExport.txt")
For i As Integer = 0 To filas.Length - 1 Step +1
valores = filas(i).ToString().Split(",")
Dim row(valores.Length - 1) As String
For j As Integer = 0 To valores.Length - 1 Step +1
row(j) = valores(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
That is what I've tried so far, but I always have an exception arising.
Thanks in advance to anyone who can give me an insight about this.
The DataTable class has built-in methods to load/save data from/to XML called ReadXml and WriteXml. Take a look at example which uses the overload to preserve the schema:
Private ReadOnly dataGridViewExportPath As String = IO.Path.Combine("C:\", "CSV", "DataGridViewExport.txt")
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
table.WriteXml(path, XmlWriteMode.WriteSchema)
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
table.ReadXml(path)
End Sub
While users can manually edit the XML file that is generated from WriteXML, I would certainly not suggest it.
This is code which writes to a text file:
speichern means to save.
Note that I use a # in my example for formatting reasons. When reading in again, you can find the # and then you know that and that line is coming...
And I used Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") to format the Date into German format, but you can decide yourself if you want that. 🙂
Note that I'm using a FileDialog that I downloaded from Visual Studio's own NuGet package manager.
Private Sub Button_speichern_Click(sender As Object, e As EventArgs) Handles Button_speichern.Click
speichern()
End Sub
Private Sub speichern()
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the text file and the program will save it .
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "store data in a text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Textdatei", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Timestamp of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu) & NewLine & NewLine) 'supposed to be line break + 2 blank lines :-)
textfile.WriteLine("your text")
textfile.WriteLine("#") 'Marker
textfile.Close()
End Using
End Sub
Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
speichern()
End Sub
And this is to read from a text file:
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Pfad, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return Nothing
For i As Integer = 0 To RAT.Length - 1 Step 1
If RAT(i) = "#" OrElse RAT(i) = "" Then Continue For
'do your work here with (RAT(i))
Next

VB.NET Program is always reading last created textfile

Trying to create a login form,
My coding is currently:
Imports System
Imports System.IO
Public Class frmLogin
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String
Dim files As Integer
Dim filepath As String
Public Structure info
Dim U As String
Dim P As String
End Structure
Dim details As info
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If txtusername.Text = details.U And txtpassword.Text = details.P Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
End Sub
Private Sub btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
files = files + 1
filepath = "C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt"
Dim di As DirectoryInfo = New DirectoryInfo("C:\Users\TheGlove\Desktop\Alex's Program")
folderpath = "C:\Users\TheGlove\Desktop\Alex's Program"
files = System.IO.Directory.GetFiles(folderpath, "*.txt").Count
For Each fi In di.GetFiles()
MsgBox(fi.Name)
Dim FILE = System.IO.File.ReadAllLines("C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt")
Dim myArray As String() = FILE
details.U = myArray(0)
details.P = myArray(1)
Next
End Sub
End Class
Button 1 will be merged with btnlogin when i get it working and for now is currently just a seperate button to read each textfile.
When each button is pressed (Button 1 -> btnlogin), only the last created textfile is correct.
By the looks of things, your code does read all the text files, but keeps overwriting details.u and details.p with the value retrieved from each file. So, when the loop gets to the last file, those values are what ends up in the details object.
I'm assuming that you want to read all the usernames and passwords into a list and check the details in the TextBoxes against that list, so .. Your code should probably be something like the code below (see the code comments for an explanation of some of the differences.
Before we get to the code, can give you a couple of pointers.
Firstly, always try to use names that are meaningful. Defining your structure as Info is not as meaningful as it could be. For example, you would be better calling it UserInfo and rather than use P and U, you would be better using Password and UserName. It may not matter so much right now, but when you start writing larger more complex programs, and have to come back to them in 6 months time to update them, info.P or details.P aren't as informative as the suggested names.
Secondly, as #ajd mentioned. Don't use magic strings. Create one definition at the beginning of your code which can be used throughout. Again it makes maintenance much easier if you only have to change a string once instead of multiple times, and reduces the chance of mistakes.
Finally, several of the variables you have defined aren't used in your code at all. Again, at this level, it isn't a major issue, but with large programs, you could end up with a bigger memory footprint than you want.
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String = "C:\Users\TheGlove\Desktop\Alex's Program"
Dim files As Integer
Dim filepath As String
Public Structure UserInfo
Dim Name As String
Dim Password As String
End Structure
'Change details to a list of info instead of a single instance
Dim userList As New List(Of UserInfo)
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
'Iterate through the list of details, checking each instance against the textboxes
For Each tempUserInfo As UserInfo In userList
If txtusername.Text = tempUserInfo.Name And txtpassword.Text = tempUserInfo.Password Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
'This is here, because after your form has opened an closed, the loop
'that checks usernames and passwords will continue. The line below exits the loop safely
Exit For
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
Next
End Sub
Private Sub Btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'clear the list of user details otherwise, if the files are loaded a second time,
'you'll get the same details added again
userList.Clear()
'This line replaces several lines in your code that searches the folder for files
'marching the search pattern
Dim fileList() As FileInfo = New DirectoryInfo(folderpath).GetFiles("loginfile*.txt")
For Each fi As FileInfo In fileList
MsgBox(fi.Name)
Dim userDetails() As String = System.IO.File.ReadAllLines(fi.FullName)
Dim tempInfo As New UserInfo With {.Name = userDetails(0), .Password = userDetails(1)}
'An expanded version of the above line is
'Dim tempInfo As New info
'tempInfo.U = userDetails(0)
'tempInfo.P = userDetails(1)
userList.Add(tempInfo)
Next
files = fileList.Count
End Sub

Importing a CSV into a combobox, then changing other things in VB

What I want to do is import a CSV file (called fwlist.txt), that looks like this:
modelname,power type,pic,part number,firmware, option1, option 1, etc
End result, i would like a combobox that shows the modelname, and when the model name is selected from the pulldown, it updates various labels and text boxes on the form with other information.
Here's what I have so far:
Dim filename As String = "fwlist.txt"
Dim pwrtype As String
Dim pic As String
Dim partnum As String
Dim lineread As String
Dim FirmwareName As String
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
FirmwareName = fields(0) 'Take First Field
cbFW.Items.Add(FirmwareName)
'Set Text labels based on position in line.
pwrtype = fields(1)
pic = fields(2)
partnum = fields(3)
(...etc through options)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
lblPwrType.Text = pwrtype
lblPic.Text = pic
lblPartNum.Text = parnum
....etc thruogh options
End Sub
This code works, but only sort of. If i select anything from the combo box, it only gives me the information from the very last line of the CSV file - even if its the first entry in the box. I'm pretty sure it's something simple that I'm messing up.. anyone help?
First we read the lines into Firmware objects then we set this List(Of Firmware) as the DataSource of the ComboBox.
Then we handle the SelectedIndexChanged event of the ComboBox which will get the currently selected firmware and loads its data to the TextBox controls.
This is a tested, working example below:
Public Class Firmware
Public Property ModelName As String
Public Property PowerType As String
Public Property Pic As String
Public Property PartNumber As String
Public Property Firmware As String
Public Property Option1 As String
End Class
Public Class MainForm
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines As String() = Nothing
Try
' Read the file in one step
lines = File.ReadAllLines("fwlist.txt")
Catch ex As Exception
Dim dialogResult As DialogResult = MessageBox.Show(Me, "File not found! Would you like to exit program?", "Error reading file", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2)
If dialogResult = DialogResult.Yes Then
Me.Close()
End If
Exit Sub
End Try
Dim firmwares As List(Of Firmware) = New List(Of Firmware)
For Each line As String In lines
Dim rawData As String() = line.Split({","}, StringSplitOptions.None)
' Create Firmware object from each line
Dim firmware As Firmware = New Firmware() With
{
.ModelName = rawData(0),
.PowerType = rawData(1),
.Pic = rawData(2),
.PartNumber = rawData(3),
.Firmware = rawData(4),
.Option1 = rawData(5)
}
' We store the read firmwares into a list
firmwares.Add(firmware)
Next
' Set the list as the data source of the combobox
' DisplayMember indicates which property will be shown in the combobox
With cboModelNames
.DataSource = firmwares
.DisplayMember = "ModelName"
End With
End Sub
Private Sub cboModelNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelNames.SelectedIndexChanged
RefreshForm()
End Sub
Private Sub RefreshForm()
' Get the selected item as Firmware object
Dim currentFirmware As Firmware = DirectCast(cboModelNames.SelectedItem, Firmware)
' Refresh all the textboxes with the information
With currentFirmware
txtPowerType.Text = .PowerType
txtPic.Text = .Pic
txtPartNumber.Text = .PartNumber
txtFirmware.Text = .Firmware
txtOption1.Text = .Option1
End With
End Sub
End Class
Every time you set the value of a variable like pwrtype, its old value is thrown away and there is no way to get it back. And even if you did save multiple values for each variable, you would need a way to figure out which value goes with the currently selected item in the combo box. To resolve these two issues you need:
a way to group values from the same line together
a way to save all values read from the file, not just the most recent ones
Let's start with the first issue, grouping values together. In the example code below, I created a Structure type called FirmwareInfo to serve that purpose. Each FirmwareInfo has its own pwrtype, pic, etc.
The other piece of the puzzle that you are missing is a way to save more than one Firmware. The easiest way to do this is to add each FirmwareInfo to the combo box's item list, instead of adding just the display string. The combo box will convert each item to a string in the UI; the ToString() method tells it how you want this conversion to be done.
I haven't run this example code so I can't guarantee there aren't mistakes in there, but hopefully it's enough to show the general idea.
Dim filename As String = "fwlist.txt"
Structure FirmwareInfo
Public pwrtype As String
Public pic As String
Public partnum As String
Public FirmwareName As String
Public Overrides Function ToString() As String
Return FirmwareName
End Function
End Structure
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
Dim lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
Dim info As New FirmwareInfo With {
.FirmwareName = fields(0),
.pwrtype = fields(1),
.pic = fields(2),
.partnum = fields(3)
}
cbFW.Items.Add(info)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
Dim currentInfo = DirectCast(cbFW.SelectedItem, FirmwareInfo)
lblPwrType.Text = currentInfo.pwrtype
lblPic.Text = currentInfo.pic
lblPartNum.Text = currentInfo.parnum
' ....etc through options
End Sub

Searching all jpg's from all drives in a computer vb.net

I want to list all JPG files from all drives in a computer with there full path.
So I tried following code but it only list few random files, it wont search all files. i got this from here: Searching a drive with vb.net
Public Sub DirSearch(ByVal sDir As String)
Dim fl As String
Try
For Each dir As String In Directory.GetDirectories(sDir)
For Each fl In Directory.GetFiles(dir, "*.jpg")
listbox1.Items.Add(fl)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
'form1 load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DirSearch("c:\")
DirSearch("d:\")
DirSearch("e:\")
DirSearch("f:\")
DirSearch("g:\")
DirSearch("h:\")
DirSearch("i:\")
DirSearch("j:\")
DirSearch("k:\")
'DirSearch("so on.....")
savetxtfile()
End Sub
Save searched result to text file in system drive
Sub savetxtfile()
Dim systemdrv As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
TextBox1.Text = listbox1.Items.Count
Dim w As IO.StreamWriter
Dim r As IO.StreamReader
Dim i As Integer
w = New IO.StreamWriter(systemdrv + "temp\test.txt")
For i = 0 To listbox1.Items.Count - 1
w.WriteLine(listbox1.Items.Item(i))
Next
w.Close()
End Sub
You're ignoring your exception...
Debug.WriteLine(ex.Message)
Use this instead (so you can't miss it for debugging)...
MessageBox.Show(ex.Message)
Knowing that what's happening is probably a folder access error, you need to handle that accordingly.
For Each dir As String In Directory.GetDirectories(sDir)
Try
For Each fl In Directory.GetFiles(dir, "*.jpg")
lstbxTest.Items.Add(fl)
Next
Catch ex As Exception
Continue For
End Try
Next
Effectively, continue if you get an error, because you don't really care in this case.
You might want to add some exceptions in there (If dir = "whatever" Then Continue For) so you're not trying to go through every single system folder in operating system.

How to work out if a file has been read in order to read the next file?

Here is my code:
Private Sub btnDisplayOrderDetails_Click(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnDisplayOrder Details.Click
Dim myStreamReader As StreamReader
Try
myStreamReader = File.OpenText("Textfile1.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch exc As Exception
Finally
If Not myStreamReader Is Nothing Then
myStreamReader.Close()
End If
End Try
If txtOrderDetails.Text = "" Then
Dim mystreamreader1 As StreamReader
Try
mystreamreader1 = File.OpenText("textfile2.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch ex As Exception
Finally
If Not myStreamReader Is Nothing Then
mystreamreader1.Close()
End If
End Try
End If
End Sub
What I would like this code to do is:
Read the first Text file upon button click, then when I've cleared the text Box (with the use of a different button which is already coded) I would then like to read in the second text file upon button click into the same Text box as before.
It's not clear what you are trying to do with the files. Combine them all into a single text box, or does each file belong to a specific textbox.
The looping method to place all the files into a single text box:
Dim filePath As String = "C:\Users\Practice\Practice\bin\Debug"
Dim sb As New StringBuilder
For Each f As String In Directory.GetFiles(filePath, "*.txt")
sb.AppendLine(File.ReadAllText(f))
Next
txtOrderDetails.Text = sb.ToString()
Or if it's not a list, then you go through your files one by one:
Dim test1 As String = Path.Combine(filePath, "Textbox1.txt")
If File.Exists(test1) Then
TextBox1.Text = File.ReadAllText(test1)
End If
Dim test2 As String = Path.Combine(filePath, "Textbox2.txt")
If File.Exists(test2) Then
TextBox2.Text = File.ReadAllText(test2)
End If