Get a list of all files inside of a directory in vb.net - vb.net

How can you obtain a list of files (as a stringcollection or some other storage method) which contains the full path on the user's computer to the files?
Is there a method for doing so?

It looks like you want to use Directory.GetFiles() in the System.IO namespace.
Docs here.

Dim txtFiles = Directory.GetFiles("C:\Input", "*.CSV", SearchOption.TopDirectoryOnly).
[Select](Function(nm) Path.GetFileName(nm))
Dim arrayList As New System.Collections.ArrayList()
For Each filenm As String In txtFiles
arrayList.Add(New clsImportFiles(filenm))
Next

Add a Listbox to Windows Form and Add following code on Form Load or other events :-
ListBox1.Items.AddRange(Directory.GetFiles("Your Directory PAth Here"))
Hope IT Helps ; From Nirav

Related

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.

How to create a dynamic excel link in VB.NET? (not .dll)

VB.NET level: Beginner
I made a .exe using VB.NET. In this program there are many links to excel files (There are specific folders for excel files).
My problem:
Consider an excel file named as abc.xlsx, which is on my home pc. Link to this file is as follows,
D:\work\data\abc.xlsx
now for obvious reasons, this link will not be valid when I run the .exe on my work pc.
(Later I want to run this .exe on multiple pc's)
How to solve this issue?
My thinking is to create a dynamic link which will update itself based on pc in use or to create a constant link which is independent of pc in use.
Help will be really appreciated.
Thanks in advance
so make the path relative to the .exe
C:\myapp\myapp.exe
c:\myapp\data\abc.xslx
...
So no matter where you app is, you can get to your data like this
Dim dataFolder As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly(‌​).Location)
dataFolder = System.IO.Path.Combine(dataFolder,"data")
Dim theFileIwant as String = System.IO.Path.Combine(datafolder,"abc.xslx")
Try something like this:
Public Function GetDynamicFilename(p_filename As String) As String
Dim tempPath As String
Select Case My.Computer.Name.ToUpper
Case "COMPUTER1"
tempPath = "c:\work\data"
Case "COMPUTER2"
tempPath = "d:\work\files"
End Select
Return String.Format("{0}\{1}", tempPath, p_filename)
End Function

How do I get resource file values in Visual Basic?

I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.
Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.
I think the issue is with the string "MyProjectName.My.Resources.Resources".
Would I be better off moving the strings into their own resource file?
I thought it was something similar to:
my.Resource.whateverhere
Is that not the kind of resources you are looking for?
Try
Global.<MyNamespace>.My.Resources.<ResourceStringName>
to access Resource Strings
Try ResourceManager("MyProjectName.Resources", ...), otherwise if it's the application resources you can simply use My.Resources.HD (see here:My.Resources Object)
or
Open Reflector, load your assembly there, go to resources, a list of resources appears, search for the one containg 'HD', copy the name (it's like MyProjectName.Resources.resources), remove the last .resources and try with that.
Refer to the MSDN article Retrieving Resources with the ResourceManager Class for naming convetions:
Dim myManager As New _
System.Resources.ResourceManager("ResourceNamespace.myResources", _
myAssembly)
If you load an external .resx file and want it to show up under intellisense My.Resources then you need to do 2 things.
First the file should be in the root of your project. Simply right click the project and do "Add Existing Item", and give it your .resx file. You should notice that there is no chevron to expand the resx file like your built-in resource file.
The last step is to highlight your resx file and go to the properties window. Under Custom Tool put "ResXFileCodeGenerator" and under the Custom Tool NameSpace put "My.Resources". You should now be able to programmatically access this resource under My.Resources.[name of the resx file].resource_item.
I was unable to access the resource file until I moved the .resx file into its own project and referenced that project from my main one. I also had to create a dummy class in that project so that it would compile into a DLL file.
The code for accessing the resource file is actually located in the generated Resource.resx.vb file.
I was able to access the resource file using the following code.
'Name of Class Library where I moved the resx file
Dim classLibraryName As String = "ResourceProj"
'Name of Resource File without the .resx suffix
Dim resourceFileName As String = "Mappings"
'Finding the assembly of the resx file, ResourceProjClass is a dummy class I created so that the dll would build.
Dim myAssembly As Assembly = GetType(ResourceProj.ResourceProjClass).Assembly
Dim rm As Resources.ResourceManager = Nothing
rm = New Resources.ResourceManager(classLibraryName & "." & resourceFileName, GetType(myAssembly)
Return rm.GetString(lookUpKey)
Simply:
Dim loginMessage As String = Global.Resources.NameOfYourResxFile.NameOFVariable

Using a .txt file Resource in VB

Right now i have a line of code, in vb, that calls a text file, like this:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("data5.txt")
data5.txt is a resource in my application, however the application doesn't run because it can't find data5.txt. I'm pretty sure there is another code for finding a .txt file in the resource that i'm overlooking, but i can't seem to figure it out. So does anyone know of a simple fix for this? or maybe another whole new line of code? Thanks in advance!
If you added the file as a resource in the Project + Properties, Resources tab, you'll get its content by using My.Resources:
Dim content As String = My.Resources.data5
Click the arrow on the Add Resource button and select Add Existing File, select your data5.txt file.
I'm assuming that the file is being compiled as an Embedded Resource.
Embedded Resources aren't files in the filesystem; that code will not work.
You need to call Assembly.GetManifestResourceStream, like this:
Dim fileText As String
Dim a As Assembly = GetType(SomeClass).Assembly
Using reader As New StreamReader(a.GetManifestResourceStream("MyNamespace.data5.txt"))
fileText = reader.ReadToEnd()
End Using
First, go to project resources (My Project --> Resources), and drag-and-drop your file, say "myfile.txt", from the file system to the resourses page.
Then:
Imports System.IO
...
Dim stream As New MemoryStream(My.Resources.myfile)
Dim reader As New StreamReader(stream)
Dim s As String = reader.ReadToEnd()

How do I create a folder in VB if it doesn't exist?

I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.
I want my program to download the apps to program files\any name here\
So basically I need a function that checks if a folder exists, and if it doesn't it creates it.
If Not System.IO.Directory.Exists(YourPath) Then
System.IO.Directory.CreateDirectory(YourPath)
End If
Under System.IO, there is a class called Directory.
Do the following:
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
It will ensure that the directory is there.
Try the System.IO.DirectoryInfo class.
The sample from MSDN:
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' Specify the directories you want to manipulate.
Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
' Determine whether the directory exists.
If di.Exists Then
' Indicate that it already exists.
Console.WriteLine("That path exists already.")
Return
End If
' Try to create the directory.
di.Create()
Console.WriteLine("The directory was created successfully.")
' Delete the directory.
di.Delete()
Console.WriteLine("The directory was deleted successfully.")
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Since the question didn't specify .NET, this should work in VBScript or VB6.
Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
objFSO.CreateFolder strFolder
End If
Try this: Directory.Exists(TheFolderName) and Directory.CreateDirectory(TheFolderName)
(You may need: Imports System.IO)
VB.NET? System.IO.Directory.Exists(string path)
Directory.CreateDirectory() should do it.
http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx
Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:
Hope that helps.
(imports System.IO)
if Not Directory.Exists(Path) then
Directory.CreateDirectory(Path)
end if
If Not Directory.Exists(somePath) then
Directory.CreateDirectory(somePath)
End If
You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.
I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.
Cheers
Just do this:
Dim sPath As String = "Folder path here"
If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
Else
'Something else happens, because the folder exists
End If
I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.
Hope it helps!
-nfell2009