How to work out if a file has been read in order to read the next file? - vb.net

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

Related

What to do to reject a replace txt file request, and offer them to create new txt file instead?

Using this codes, I don't know what's wrong, I still can't solve my problem
Please check and correct me.
What's wrong?
What I want is when they click the savefile button, savefiledialog will show to save the data to a file. If they try to replace an existing file, Msgbox will show to reject their replace request. So they have to create new file.
With this code, this is what's happening.
1st click, you can create or replace without getting reject messagebox.
2nd click, you will receive rejection either you create or replace.
3rd click is like the 1st click
4th click is like the 2nd click
And so on.
Private lastSaveFileName As String = String.Empty
Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
lastSaveFileName = GetSaveFileName2(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.AppendAllText(lastSaveFileName, txtdisplay1.Text)
End If
End Sub
Private Function GetSaveFileName2(ByVal suggestedName As String) As String
Using sfd3 As New SaveFileDialog()
sfd3.Filter = "Text Files (*.txt) |*.txt"
sfd3.FileName = suggestedName
sfd3.OverwritePrompt = False
If sfd3.ShowDialog() = DialogResult.OK Then
If Not File.Exists(lastSaveFileName) Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
Else
Return sfd3.FileName
End If
Else
End If
Return String.Empty
End Using
End Function
This is related to my first post,
How to WriteAllText but restrict to overwrite the existing file?
Like this,
Private Function GetSaveFileName2(suggestedName As String) As String
Dim rv As String = String.Empty 'String.Empty is do not save
Dim sfd3 As New SaveFileDialog()
sfd3.Filter = "Text Files (*.txt) |*.txt"
sfd3.FileName = suggestedName
sfd3.OverwritePrompt = False
Dim dr As DialogResult
Do
dr = sfd3.ShowDialog
If dr = DialogResult.OK Then
If IO.File.Exists(sfd3.FileName) Then
MessageBox.Show("Not saved! .... Please create new file to save new records or Cancel to Exit.",
"Save error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
rv = sfd3.FileName
End If
End If
Loop While dr = Windows.Forms.DialogResult.OK AndAlso rv = String.Empty
Return rv
End Function

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

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

Listview multi lines

I created a program to load a text file, should load all lines from the textfile and display them in the listview
However It only loads the first line in the listview how do I get it to read the entire file?
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
Dim Path As String = OpenFD.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
Dim lv As New ListViewItem
For Each Line As String In ItemLines.Lines
List.Items.Add(lv)
lv.Text = Line
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
Next
Catch ex As Exception
End Try
End Sub
One possible solution could look like this:
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
' full path to the file + name
Dim filename As String = OpenFD.FileName
Try
' check if file exists to prevent errors
if (File.Exists(filename)) then
' fetch complete text into as lines
Dim Lines = File.ReadAllLines(filename)
' iterate over each line
For Each Line As String In Lines
Dim lv as new ListViewItem
' take it
lv.Text = Line
' and use it
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
' show it
List.Items.Add(lv)
Next
end if
Catch ex As Exception
' inform the user resp. developer
Console.WriteLine(String.Format("An error occurred: {0}", ex.Message))
End Try
End Sub
As already mentioned use File.ReadAllLines if you want to read the file line by line and don't suppress errors - inform the user or at least the developer (yourself, using a log file or something appropriate).

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

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"