open/import multiple files vb.net - vb.net

ok im going to try to explain this the best i can.
So i have a list viewer for image thumbnails.
I need to be able to click a button and it load the full dir. The issue is the normal way loads the images in but they are out of order. 1.jpg 10.jpg 100.jpg
For Each file As String In My.Computer.FileSystem.GetFiles(appPath + "\" + ConfigurationManager.AppSettings("activedisplay").ToString + "\" + Bfolder.Text + "\")
ImageListView1.Items.Add(file)
Next
So i went and looked around for a filter
Dim files = Directory.EnumerateFiles(appPath + "\" + ConfigurationManager.AppSettings("activedisplay").ToString + "\" + Bfolder.Text + "\").
Select(Function(s) Path.GetFileName(s)).ToList
Console.WriteLine("Before: {0}", String.Join(", ", files))
' sort the list using the Natural Comparer:
files.Sort(myComparer)
MsgBox((String.Join(", ", files)))
So this script puts them in the right order 1,2,3,4,5.. but i cant figure out how to open it this way. Cause
ImageListViewer1.items.addrange((String.Join(", ", files)))
overloads.
Like openFileDialog.FileNames has the ability to open multiple files at once so I know its possible but i don't want to use a dialog.
To the point i need a way to load the file string produced by this which is 1.jpg,2.jpg,3.jpg into the ImageViewerList.
This creates a string of the file in the correct order "(String.Join(", ", files))" is there a way i can load files from a string.
For Each file As String In My.Computer.FileSystem.GetFiles(appPath, string
and it be able to load the string of files it creates the string like so
1.jpg,2.jpg,3.jpg continued for all files in the dir it looked at
iv looked around google for assistance and looked at the ms page on getfiles but i have had no luck.
any ways any help would be greatly appreciated
thanks in advance
-Fox

You need to write your own sort function to sort the numeric values.
I referred the link, for CustomSort function. Below code sorts the file names and works nicely for me.
Dim Dir As String = appPath + "\" + ConfigurationManager.AppSettings("activedisplay").ToString + "\" + Bfolder.Text + "\"
Dim fileList = New DirectoryInfo(Dir).GetFiles("*.jpg").[Select](Function(o) o.Name).ToList()
Dim sortedList = CustomSort(fileList).ToList()
Public Shared Function CustomSort(list As IEnumerable(Of String)) As IEnumerable(Of String)
Dim maxLen As Integer = list.[Select](Function(s) s.Length).Max()
Return list.[Select](Function(s) New With { _
Key .OrgStr = s, _
Key .SortStr = Regex.Replace(s, "(\d+)|(\D+)", Function(m) m.Value.PadLeft(maxLen, If(Char.IsDigit(m.Value(0)), " "c, "?"c))) _
}).OrderBy(Function(x) x.SortStr).[Select](Function(x) x.OrgStr)
End Function

Related

VB.NET Path to file with unknown file extension (but known name)

Could anyone help me with getting file path when I know file name (which is constant and won´t change) but don´t know file extension (can change depending on users selection in Excel):
Dim MyAppPath As String = My.Application.Info.DirectoryPath
Dim ExcelfilePath As String = IO.Path.Combine(MyAppPath, "bundle\" & "Rozpis.xlsm")
Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis.xlsm")
I want it to be like this - to match any file with this particular name "Rozpis":
Dim MyAppPath As String = My.Application.Info.DirectoryPath
Dim ExcelfilePath As String = IO.Path.Combine(MyAppPath, "bundle\" & "Rozpis.*")
Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis.*")
(This code is part of simple "self-protecting" mechanism for my app.)
What I tried:
I looked at regex (but if there is simpler way than regex it would be better - tried filemame.* - not working) as potential option (specifically this one: /(.)+(doc|docx|pdf)$/i ) but I don´t know much how to use it. I got error Regex cannot be converted to string when tried to use like this:
// Don´t remember the code exactly - something like this:
// regex = New Regex as regex
Dim ExcelfilePath As String = IO.Path.Combine(MyAppPath, "bundle\" & "Rozpis." & regex)
Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis" & regex)

Count words in an external file using delimiter of a space

I want to calculate the number of words in a text file using a delimiter of a space (" "), however I am struggling.
Dim counter = 0
Dim delim = " "
Dim fields() As String
fields = Nothing
Dim line As String
line = Input
While (SR.EndOfStream)
line = SR.ReadLine()
End While
Console.WriteLine(vbLf & "Reading File.. ")
fields = line.Split(delim.ToCharArray())
For i = 0 To fields.Length
counter = counter + 1
Next
SR.Close()
Console.WriteLine(vbLf & "The word count is {0}", counter)
I do not know how to open the file and to get the do this, very confused; would like an explanation so I can edit and understand from it.
You're going to be reading a file as the source of the data, so let's create a variable to refer to its filename:
Dim srcFile = "C:\temp\twolines.txt"
As you have shown already, a variable is needed to hold the number of words found:
Dim counter = 0
To read from the file, a StreamReader will do the job. Now, we look at the documenation for it (yes, really) and notice that it has a Dispose method. That means that we have to explicitly dispose of it after we've used it to make sure that no system resources are tied up until the computer is next rebooted (e.g there could be a "memory leak"). Fortunately, there is the Using construct to take care of that for us:
Using sr As New StreamReader(srcFile)
And now we want to iterate over the content of the file line-by-line until the end of the file:
While Not sr.EndOfStream
Then we want to read a line and find how many items separated by spaces it has:
counter += sr.ReadLine().Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Length
The += operator is like saying "add n to a" instead of saying "a = a + n". The {" "c} is a literal array of the character " "c. The c tells it that is a character and not a string of one character. The StringSplitOptions.RemoveEmptyEntries means that if there was text of "one two" then it would ignore the extra spaces.
So, if you were writing a console program, it might look like:
Imports System.IO
Module Module1
Sub Main()
Dim srcFile = "C:\temp\twolines.txt"
Dim counter = 0
Using sr As New StreamReader(srcFile)
While Not sr.EndOfStream
counter += sr.ReadLine().Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Length
End While
End Using
Console.WriteLine(counter)
Console.ReadLine()
End Sub
End Module
Any embellishments such as writing out what the number represents or error checking are left up to you.
With Path.Combine you don't have to worry about where the slashes or back slashes go. You can get the path of special folders easily using the Environment class. The File class of System.IO is shared so you don't have to create an instance.
Public Sub Main()
Dim p As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Chapters.txt")
Debug.Print(Environment.SpecialFolder.MyDocuments.ToString)
Dim count As Integer = GetCount(p)
Console.WriteLine(count)
Console.ReadKey()
End Sub
Private Function GetCount(Path As String) As Integer
Dim s = File.ReadAllText(Path)
Return s.Split().Length
End Function
Use Split function, then Directly get the length of result array and add 1 to it.

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.

Delete multiple files

I'm trying to delete multiple files in same folder with vb.net, but I haven't succeed yet. Help please?
I tried
Dim FileToDelete1 As String
Dim FileToDelete2 As String
Dim FileToDelete3 As String
Dim FileToDelete4 As String
Dim FileToDelete5 As String
FileToDelete1 = Application.StartupPath & "\1.exe"
FileToDelete2 = Application.StartupPath & "\2.dll"
FileToDelete3 = Application.StartupPath & "\3.dll"
FileToDelete4 = Application.StartupPath & "\4.dll"
FileToDelete5 = Application.StartupPath & "\5.dll"
If System.IO.File.Exists( FileToDelete1 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete1 )
ElseIf System.IO.File.Exists( FileToDelete2 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete2 )
ElseIf System.IO.File.Exists( FileToDelete3 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete3 )
ElseIf System.IO.File.Exists( FileToDelete4 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete4 )
ElseIf System.IO.File.Exists( FileToDelete5 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete5 )
End If
Several problems here.
First, File.Exists returns a Boolean value.
The "=True" is unnecessary because you're basically asking if True=True. Fortunately, it is.
Second, file existence or not it's not the only way to fail. For instance, if the file is in use, you'll get an exception. You should handle it.
Third, what if you need to delete a thousand files? Would you create a String for each one of them? There are better options, for instance, the GetFiles method which will return a ReadOnly List of Strings, each one representing one file.
I don't know your needs, but to catch the files you mention, the following call can be made:
FileIO.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchTopLevelOnly, {"?.exe", "?.dll"})
It will get every EXE and DLL file if it's name consists in only one character.
Finally, notice that if the first condition is met, no other will be evaluated, hence no other file will be deleted.
With that implementation you'll need to run the program 5 times in order to delete every file.
GetFiles method solves this as well.
Additionally, consider importing namespaces so you don't need to prefix them in every method call.
Looks like you want to do some thing like this
Dim fileNames() as string={"1","2","3"}
Dim fileTypes() as string={"exe","dll"}
directory.SetCurrentDirectory(Application.StartupPath)
For each fileName as string in fileNames
For each fileType as string in fileTypes
if My.Computer.FileSystem .FileExists (fileName &"."& fileType) then
try
My.Computer.FileSystem.DeleteFile( fileName &"."& fileType )
catch ex As Exception
'**** processings related with exception.
end try
endif
'Dim files() As String = Directory.GetFiles(dirPath, fileName &"." & fileType, SearchOption.AllDirectories)
'For Each FileToDelete as string in files
' My.Computer.FileSystem.DeleteFile( FileToDelete )
'Next
Next
Next

Extract filename from path [duplicate]

This question already has answers here:
How to extract file name from path?
(16 answers)
Closed 1 year ago.
I need to extract the filename from a path (a string):
e.g.,
"C:\folder\folder\folder\file.txt" = "file" (or even "file.txt" to get me started)
Essentially everything before and including the last \
I've heard of using wildcards in place of Regex (as it's an odd implementation in VBA?) but can't find anything solid.
Cheers in advance.
I believe this works, using VBA:
Dim strPath As String
strPath = "C:\folder\folder\folder\file.txt"
Dim strFile As String
strFile = Right(strPath, Len(strPath) - InStrRev(strPath, "\"))
InStrRev looks for the first instance of "\" from the end, and returns the position. Right makes a substring starting from the right of given length, so you calculate the needed length using Len - InStrRev
Thanks to kaveman for the help. Here is the full code I used to remove both the path and the extension (it is not full proof, does not take into consideration files that contain more than 2 decimals eg. *.tar.gz)
sFullPath = "C:\dir\dir\dir\file.txt"
sFullFilename = Right(sFullPath, Len(sFullPath) - InStrRev(sFullPath, "\"))
sFilename = Left(sFullFilename, (InStr(sFullFilename, ".") - 1))
sFilename = "file"
I was looking for a solution without code. This VBA works in the Excel Formula Bar:
To extract the file name:
=RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"\","~",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))
To extract the file path:
=MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))))
`You can also try:
Sub filen()
Dim parts() As String
Dim Inputfolder As String, a As String
'Takes input as any file on disk
Inputfolder = Application.GetOpenFilename("Folder, *")
parts = Split(Inputfolder, "\")
a = parts(UBound(parts()))
MsgBox ("File is: " & a)
End Sub
This sub can display Folder name of any file
Here's simpler method: a one-line function to extract only the name — without the file extension — as you specified in your example:
Function getName(pf):getName=Split(Mid(pf,InStrRev(pf,"\")+1),".")(0):End Function
...so, using your example, this:
       MsgBox getName("C:\folder\folder\folder\file.txt")
  returns:
       
For cases where you want to extract the filename while retaining the file extension, or if you want to extract the only the path, here are two more single-line functions:
Extract Filename from x:\path\filename:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function
Extract Path from x:\path\filename:
Function getPath(pf)As String: getPath=Left(pf,InStrRev(pf,"\")): End Function
Examples:
(Source)
Using Java:
String myPath="C:\folder\folder\folder\file.txt";
System.out.println("filename " + myPath.lastIndexOf('\\'));
I used kaveman's suggestion successfully as well to get the Full File name but sometimes when i have lots of Dots in my Full File Name, I used the following to get rid of the .txt bit:
FileName = Left(FullFileName, (InStrRev(FullFileName, ".") - 1))
You can use a FileSystemObject for that.
First, include a reference for de Microsoft Scripting Runtime (VB Editor Menu Bar > Tools > References).
After that, you can use a function such as this one:
Function Get_FileName_fromPath(myPath as string) as string
Dim FSO as New Scripting.FileSystemObject
'Check if File Exists before getting the name
iF FSO.FileExists(myPath) then
Get_FileName_fromPath = FSO.GetFileName(myPath)
Else
Get_FileName_fromPath = "File not found!"
End if
End Function
File System Objects are very useful for file manipulation, especially when checking for their existence and moving them around. I like to use them early bound (Dim statement), but you can use them late bound if you prefer (CreateObject statement).
'[/vba]
' Keep It Simple
' .. why use FileSystemObject or Split when Left and Mid will do it
' the FSO has some 33 Subs or Functions
that have to be loaded each time it is created.
' and needs the file to exist ... yet is only a bit slower
... under twice time.. some good code in FSO
' conservation is good .. spare a few electrons. ????... save a few millionths of a sec
'Also
' .. why the format of a function that we all seem to use like
'
' .. Function GetAStr(x) as string
' dim extraStr as string
' a lot of work with extraStr..
' that could have been done with the string variable GetAStr
already created by the function
' then .. GetAStr=extraStr to put it in its right place
' .. End Function
Function GetNameL1$(FilePath$, Optional NLess& = 1)
' default Nless=1 => name only
' NLess =2 => xcopya.xls xcopyb.xls xcopy7.xlsm all as xcopy to get find latest version
' Nless = - 4 or less => name with name.ext worka.xlsm
GetNameL1 = Mid(FilePath, InStrRev(FilePath, "") + 1)
GetNameL1 = Left(GetNameL1, InStrRev(GetNameL1, ".") - NLess)
End Function
Function LastFold$(FilePath$)
LastFold = Left(FilePath, InStrRev(FilePath, "") - 1)
LastFold = Mid(LastFold, InStrRev(LastFold, "") + 1)
End Function
Function LastFoldSA$(FilePath$)
Dim SA$(): SA = Split(FilePath, "")
LastFoldSA = SA(UBound(SA) - 1)
End Function
[<vba]