How can I get the names a files inside a directory - vb.net

Good day all
I have a test path name ""C:\test". There are the following folders in my directory:
importantStuff
UselessStuff
TopSecret
My question is this: How can I have Visual Basic return these exact names if I input the path "C:\test"? I have tried to use Directory.GetFiles(path), but it returns the path of those folders, and not their names. I'm stuck with this.
Just as a note: I am trying to port a program I wrote in python to vb.net. In python there is the function os.listdir(path). I essentialy want the vb.net equivalent of this

Try this
Dim direct As New DirectoryInfo(".\")
'Get the files based on .txt extension
Dim files As FileInfo() = direct.GetFiles("*.*")
'loop through each files and add it to Listbox control
For Each file As FileInfo In files
ComboBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name))
Next

Related

VB.NET open a Text File within the same folder as my Forms without writing Full Path

I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)

Missing txt file from Visual Basic

I am working in Visual Basic 2017. I have tried to add the file to the Debug folder, but then it just shows that the txt file ienter image description heres missing. I don't have the option under the "Word Solution".. How can I make the file show up? It keeps telling me it doesn't exist.
Dim inFile As IO.StreamReader
Const FileName As String = "words.txt"
Dim subscript As Integer
You can get the path of the directory (Debug or Release or any other) of the *.exe file with:
Dim directory as String = My.Application.Info.DirectoryPath
Using this information, you can then construct the full path with
Dim path As String = IO.Path.Combine(directory, FileName)
If IO.File.Exists(path) Then
...
You can check in Windows File Explorer to see where the file actually is (notice the Copy Path on the ribbon). In File Explorer you will see that the .exe you are running is down 2 directories from the Words Project directory. The double dots in the path is an old DOS way to navigating around directories without having to type out the whole path. This tells the compiler to find the file up 2 directories from the current directory.
For testing purposes this will work. For a release version you could add the file to Resources and access it the same way in any version.
You don't need a stream for a text file. .ReadAllLines returns an array of the lines in the text file
Private Sub OpCode()
Dim words = File.ReadAllLines("..\..\words.txt")
End Sub

Grabbing current user.config path (Visual Basic)

Is there a way of grabbing the location of the My.Settings user.config location? So for example I want to be able in VB to grab the path of the user.cofing file path to a string
The reason I ask is that I have an application where the user.config file is backed up and then restored, the issue is that with the my.settings folder structure it uses a unique hash with the folder name meaning that I cannot write into the code a static folder path, instead I need to be able to grab the location of the user.config OR be able to get the folder name of the application AppData.
Any ideas?
To put this in perspective, currently I'm using something like this:
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\My_App\My_App.exe_Url_<the_hash_that_changes_causing_issues>\1.0.0.0\user.config"
Because of the hash change this will not always work
Try executing this code:
Dim mainConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim userConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)
Dim userLocalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
Console.WriteLine(mainConfig.FilePath)
Console.WriteLine(userConfig.FilePath)
Console.WriteLine(userLocalConfig.FilePath)
You'll need to reference System.Configuration.dll and import System.Configuration.

Zip multiple files to one folder

So I am having trouble trying to reconcile this concept as every change I do doesn't seem to fix the issue.
I have multiline textbox and can enter multiple values separated by commas and here are the details:
Each value represents a folder
And each folder has multiple documents/other folders inside
All of these values are in one main directory (lets call it folder path)
For example say I enter in my textbox "65635,65636" each of those represent a folder in the directory i.e. "\folderpath\65635" and "\folderpath\65636", I am trying to zip these whole folders via DotNetZiplib, I know how to do this if I specifically reference one folder but is there anywhere to loop through the textbox to get the names of the folders and have the files added to one zipped folder?
Using zip As New ZipFile = new ZipFile
Dim files() As String = Directory.GetFiles(folderpath & textboxvalue)
For each textboxvalue in directory.getfiles
zip.Addfile(textboxvalue)
The zipfile function I have would know to loop through these as opposed to assuming it's one big file.
You must split textbox values in array first to get numbers separated by comma. Next you will need Combine your folder with this splited text values, creating path correctly.
Check if folder exists in system if Yes then get all files from Directory and for each filename zip it.
Something like this:
Using zip As New ZipFile("your zip filename")
For Each str As String In textboxvalue.Split(",")
Dim path as String = System.IO.Path.Combine(folderpath, str)
If System.IO.Directory.Exists(path) = False Then
Continue For
End If
Dim files() As String = Directory.GetFiles(path)
For Each fileName As String In files
zip.Addfile(fileName)
Next
Next
End Using

Get a VB 2008 file path relative to the published executable location

I have a Visual Basic Studio 2008 project that I need to deploy in 3 separate server environments. Each of those environments has a different filepath for file storage, but other than that the execution of the programs will be exactly the same in all environments.
In order to accomplish this, I'd like to instruct the program to look at a text file in the same folder as itself for the file storage file path for its environment; then i can just clone the same VB program 3 times and change the contents of the text files whenever the storage locations change.
Before publishing an executable file, I can store the text file in the bin->debug folder and use any of the VB relative path methods that I've come across (App.Path, System.IO.getcurrentdirectory, My.Application.info.directoryPath, etc) to access it with no problem. When I publish the project, however, these find the relative path of the program as buried deep within the installed user's appdata. I want to access the text file on the server where the user goes to run the executable.
So my question is: how can i get the filepath of the published executable location? I have searched for 4 hours and have been unsuccessful in finding an answer.
Relevant code:
dim fso as new scripting.filesystemobject
dim ts as scripting.textStream
ts = fso.opentextfile(My.Application.Info.DirectoryPath & "\HostFiles\rootDir.txt")
rootDir = ts.ReadAll
topDir = rootDir & 'rest of file storage location
Maybe you could try this if you are using VB.Net:
Application.StartupPath
Eg:
Dim strContent As String = IO.File.ReadAllText(Application.StartupPath & "\HostFiles\rootDir.txt")