VB How Do I Get A List of Files in a Specified Directory - vb.net

I think this is a simple question but I can't get the statement format working. I want to list all the files in a specified directory and sub-directories in a list box. I know this is pretty basic. I searched on the Microsoft doc site and I believe that I want to use the GetFile method below. My problem is that I don't know where I put the directory name.
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments)
listBox1.Items.Add(foundFile)
Next

Dim folderPath As String 'Set folder path here
Dim folder As New DirectoryInfo(folderPath)
Dim files = folder.GetFiles()
With listBox1
.DisplayMember = "Name"
.ValueMember = "FullName"
.DataSource = files
End With
Pretty much always bind as a first option. Adding item by item is generally inferior. The DisplayMember is the property or column to display and the ValueMember is the property or column to expose via the control's SelectedValue. You can set the folderPath to whatever you want, however you want, e.g. let the user choose using a FolderBrowserDialog.

Send all the file names of a directory to a text file :
Imports System.IO
'no need:
'Imports System.Linq
Dim MyFiles As String()
MyFiles = Directory.GetFiles(MyPath).
Select(Function(f) Path.
GetFileNameWithoutExtension(f)).ToArray()
' or WITH extension:
' GetFileName
File.WriteAllLines(MyPath & "Text.txt", MyFiles)

Related

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

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 read files in folders?

I am trying to get my application to check for folders in the folderbrowserdialogs selectedpath and then get those files, but it doesn't work I have tried both listed ways below. The second way gives me an error: (Expression is of type char which is not a collection type)
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles(folder)
Label1.Text = counter.Count.ToString
Next
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
For Each foundfile In folder
counter = My.Computer.FileSystem.GetFiles(foundfile)
Label1.Text = counter.Count.ToString
Next
Any help is appreciated.
FolderBrowserDialog1.SelectedPath will return the path the user selected in the dialog. You still need to write code to go get the files. There may not be a need to get the folders and then files in them. Net has ways to do that for you:
FolderBrowserDialog1.ShowDialog()
Dim myPath As String = FolderBrowserDialog1.SelectedPath
' get all files for a folder
Dim files = Directory.GetFiles(myPath)
' get all files for all sub folders
Dim files = Directory.GetFiles(myPath, "*.*",
System.IO.SearchOption.AllDirectories)
' get certain file types for folder and subs
Dim files = Directory.GetFiles(myPath, "*.jpg",
System.IO.SearchOption.AllDirectories)
You also are not going to be able to simply assign the results to a ReadOnlyCollection like that, because they are ReadOnly. The collection needs to be created/instanced with the complete list:
Dim counter As new ReadOnlyCollection(Of String)(files)

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.

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 ...