Read Multiple Files Into List View VB.Net - vb.net

I need to require the user of this program to select two text files from any directory. I then need to display them in a List View, which I have built. File 1 needs to load into the first column and File 2 needs to load into the second. They will correspond to each other.
I currently have the following to allow multiselect
OpenFileDialog.Multiselect = True
What I am having trouble with is separating these unique files into corresponding columns. For example, the following code very effectively loads the first file's contents into the first column:
Dim fileName As String = OpenFileDialog.FileName
fileReader = New StreamReader(fileName)
Do While fileReader.Peek() <> -1
firstFile = fileReader.ReadLine & vbNewLine
ListView1.Items.Add(firstFile)
Loop
When I choose the second file, the first file's contents are replaced within the same column by the second file's contents.
I have looked at using an array, but am unsure how to load the unique files into each index.
I'm not really sure where to go from here.

When you use
OpenFileDialog1.Multiselect = true
All selected files are already stored as a collection in OpenFileDialog1.FileNames, just loop through all values and put them into the listview
ListView1.Items.Clear
Dim file as string
For Each file in OpenFileDialog1.FileNames
ListView1.Item.Add(file)
Next
if you want to show the file content in different columns, then you may need to change a little bit of your code
Dim fileName As String = OpenFileDialog.FileName
fileReader = New StreamReader(fileName)
Dim FileItem As New ListViewItem
Do While fileReader.Peek() <> -1
firstFile = fileReader.ReadLine & vbNewLine
FileItem .SubItem.Add(firstFile)
Loop
ListView1.item.add(Item)
However you may need to declare the columns in the ListView1 before adding any item. If not columns define in your ListView1, then it is not possible to show the columns even you have put your file content into the subItem

Related

How to keep the content of ListBox in Vb.net

If i want to keep the content of a textbox i do this
TextBox1.Text = TextBox1.Text & Something
Is there a way to do the same thing for the content of Items of a Listbox?
In my RichTextBox3 i have the list of files in the C:\Work directory
I Tried this code but it's giving me The content of the last line (It's not adding the lines before)
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop
Help is appreciated
Thanks to all of you
I'm not sure that this will address your stated problem but there's a serious issue with that code and I need to provide a long code snippet to address it and that won't be readable in a comment.
The Lines property of a TextBox or RichTextBox is not "live" data, i.e. it doesn't refer to an array stored within the object. Each time you get the property, a new array is created. You are getting RichTextBox3.Lines twice for every iteration of that loop, so that's obviously wrong. You also should not be adding items to the ListBox one by one like that. You should be creating a list of all the items first, then adding them all with a single call to AddRange:
Dim files As New List(Of FileInfo)
For Each line In RichTextBox3.Lines
Dim folderPath = Path.Combine("C:\Work", line)
Dim folder As New DirectoryInfo(folderPath)
files.AddRange(folder.GetFiles("*", SearchOption.AllDirectories))
Next
ListBox1.Items.AddRange(files.ToArray())
If that code doesn't work as expected, you can debug it and view the contents of files at various stages to make sure that you are getting the files you expect. It might also be worth testing folder.Exists before calling GetFiles, unless you're absolutely sure that each line in the RichTextBox represents an existing folder.
This will do what you want.
number = 0
ListBox1.items.clear()
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop

Add Subfolder names to Listview

I have Combobox, and I select folder names in It. This folder has to be searched first. In these folders are also folders named "Versions"- and these folders have another folders which I need to add on Listview. I tried this but nothing is added to my Listview:
Dim Folder_To_Search As String() = IO.Directory.GetDirectories("D:\", MyCombo.Text, System.IO.SearchOption.AllDirectories)
For Each folder As String In Folder_To_Search
ListView1.Items.Add(Path.GetFileName(folder + "\Versions\"))
Next
I guess I'm missing something after + "\Versions\", can somebody give me a clue ?
Nothing is being added to your listview because GetDirectories returns, as its name implies, directories. So you're getting your list of directories and then using Path.GetFilename on each of them, but the directories do not have a filename at the end of them so only empty strings are being added to your listview.
Edit for Comment: Then it sounds like you need to run basically two nested directory searches; the first one for folders like "Microsoft" and the second for "Versions" within Microsoft folders, then loop through and get the files:
Dim TopLevelDirectories As String() = IO.Directory.GetDirectories("D:\", "*" & MyCombo.Text & "*", System.IO.SearchOption.AllDirectories)
For Each tlDir As String In TopLevelDirectories
Dim SubLevelDirectories As String() = IO.Directory.GetDirectories(tlDir, "*Versions*", System.IO.SearchOption.AllDirectories)
For Each slDir As String In SubLevelDirectories
Dim dInfo As DirectoryInfo = New DirectoryInfo(slDir)
Dim fInfo() As FileInfo = dInfo.GetFiles
For Each f As FileInfo In fInfo
ListView1.Items.Add(f.FullName) 'or ListView1.Items.Add(f.Name)
Next
Next
Next
If I understand your goal correctly, the code above should find all the files you're looking for. I made some test folders and threw Microsoft/Versions in at different levels of the directories and this code picked them all up

How to make textfile to save in program directory in Visual Studio

As i have abandoned the array approach to the problem, i need to know how to make listbox to save in textfile always in program's directory so it can be used/accessed to populate a different listbox, any ideas? Below is my code.
SaveFileDialog1.Filter = "Text files (.txt)|.txt"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName <> "" Then
Using SW As New IO.StreamWriter(SaveFileDialog1.FileName, False)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End If
A little bit of research on your part would've helped you understand what you are trying to accomplish better.
How do I get Program Data directory? My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
How do I Write multiple lines to file? File.WriteAllLines()
How do I Read multiple lines from a file? File.ReadAllLines()
Once you understand the basics you can easily put them together
Create two List boxes, and one button on your WinForm:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.
'Get the Program Data Directory (This is hidden by default by the OS.)
Dim strPath As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Dim fileName As String = "myFile.txt"
Dim fullPath = Path.Combine(strPath, fileName)
Dim data As String() = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
'Save the items to ListBox1 First
For Each item As String In data
ListBox1.Items.Add(item)
Next
'Now write the items to the textfile, line by line.
File.WriteAllLines(fullPath, data)
'Read all lines we just saved and load them onto an array of strings.
Dim tempAllLines() As String = File.ReadAllLines(fullPath)
'Display each on ListBox2 by iterating the array.
For Each line As String In tempAllLines
ListBox2.Items.Add(line)
Next
End Sub
Here, I created this form so you can get an idea of what i'm referring to.
You can get the path to the current executable's folder like this:
folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
However, that will only work if the executable is a .NET assembly. Otherwise, you could use the first argument in the command line (which is the full executable file path), like this:
folderPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()(0))
If, on the other hand, you want to get the path of the current assembly (which may be different than the executable that loaded it) you could do this:
folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Or, if you want to just get the current directory, you could use this:
folderPath = Directory.GetCurrentDirectory()
Once you have the folder path, you can add the file name to it with Path.Combine, like this:
filePath = Path.Combine(folderPath, fileName)
However, it's not recommended that you write data directly to the program's running path, since the user may not have permission to write to that folder. Using the program data folder would certainly be better, but even that can be risky:
folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyAppName")
The recommended place to store data from .NET apps is Isolated Storage.

Saving Columns of listview in VB with separator

So I have a listview which has two columns. the listview view is details.
I have successfully imported a file into the list view with correct splits. The code i used is,
Using sr As StreamReader = File.OpenText( file path )
While (-1 < sr.Peek())
Dim line As String = sr.ReadLine()
Dim item As New ListViewItem(line.Split(":"c))
ListView1.Items.Add(item)
End While
sr.Close()
End Using
So this imports the lines from my file to the program into correct columns with : as split.
Now I also have a option for users to add data from my program to the file the same way, I used this code,
Using sw As StreamWriter = File.AppendText(file path)
For Each item As ListViewItem in ListView1
Dim line As String = Nothing
For Each entry As String in item.SubItems
line.Append(entry & ":")
Next For
sw.WriteLine(line)
Next For
sw.Close()
End Using
Taken from : Separating text from .txt into colums in listview (VB.net mobile)
But my bad, vb gives this error,
Error 1 Expression is of type 'System.Windows.Forms.ListView', which is not a collection type. C:\Users\xxxx\documents\visual studio 2012\xxxxx\Form1.vb 97
I am not sure why i am getting this error, is it because of my list views properties ?
I want to be able to save the data to the text file when user click a button.
This line:
For Each item As ListViewItem in ListView1
should be this:
For Each item As ListViewItem in ListView1.Items
and this line:
For Each entry As String in item.SubItems
should be this:
For Each entry As ListViewItem.ListViewSubItem in item.SubItems
You then get a String from the Text property of the subitem.

VB.NET - Adding items to a listview as well as checkboxes and tag property

I've got this code which basically loops through a set of folders and subfolders and finds specific file types. And then lists these in a listview. Now, it's intended to list exe and msi files. And I've made it so that these icons can be doubleclicked after they have been listed. I do this by adding the path to the file in it's tag property.
But, my superiors want a checkbox next to each item. So that they can check each item they want installed. And then have a button which runs the path in each tag property one at a time. It's basically the part where I fill the listview with the checkbox, filename of the exe or msi file, tag and the icon that I'm wondering about.
This is the existing code. This includes just a Tile view of the listview.
Public Sub getDirectories(ByVal strFilepath As String, ByVal strFileExtension As String, ByVal objControl As Object)
'Load first files from the root folder. Then loop each subfolder
Dim di As New DirectoryInfo(strFilepath)
Dim aryFi As IO.FileInfo() = di.GetFiles(strFileExtension, SearchOption.AllDirectories)
Dim filePath As String
Dim fileIcon As Icon
' For each file in the root folder
For Each file In aryFi
If file.Extension = String.Empty Then
Else
filePath = GetAssociatedProgram(file.Extension)
On Error Resume Next
'Extract icon
fileIcon = Drawing.Icon.ExtractAssociatedIcon(filePath)
'Add the icon if we haven't got it already
objControl.StateImageList = Form1.iconList
If Form1.iconList.Images.ContainsKey(filePath) Then
Else
Form1.iconList.Images.Add(filePath, fileIcon)
End If
'Add item to list
objControl.items.add(file.Name, filePath).Tag = file.DirectoryName
End If
Next
End Sub
Basically I call this sub in this way:
getDirectories(strProgramLocation, "*.exe", Form1.listViewSupSoftware)
And I've found that I can add items to a listview which also contains columns:
Dim tempstr(2) As String
tempstr(0) = "Name of item"
tempstr(1) = "Target folder of item"
Dim tempNode As ListViewItem
tempNode = New ListViewItem(tempstr)
Form1.listViewItem.Items.Add(tempNode)
But there should be a way of combining these two right? I'm not sure how I can add a checkbox in the first column of the listview? I've already set the Checkbox property of the listview to True. But I could use some pointers here if anyone's got any. :)
Mmm, I don't understand quite well your question. If you already have the listbox you just need to use a CheckedListBox and loop thru all the checked items executing the executable stored into the tag property ...
As I said I'm not sure If I get what you mean ...