Files in directory sort by fileName ascending - for each - vb.net

How to update my code so that all files are processed in order of date/time created?
Private Sub StartupFindExistingFiles(Path As String, SearchPattern As String)
Dim fileEntries As String() = Directory.GetFiles(Path, SearchPattern)
For Each fileName As String In fileEntries
PrintJOBFile(fileName)
Next
End Sub

You could use LINQ with File.GetCreationTime:
Dim orderedByCreation = From file In Directory.EnumerateFiles(Path, SearchPattern)
Let createdAt = System.IO.File.GetCreationTime(file)
Order By createdAt Ascending
Select file
For Each filePath As String In orderedByCreation
PrintJOBFile(filePath)
Next
Note that you could also use GetFiles instead of EnumerateFiles. The latter can be more efficient.

Related

How to delete files containing string from listbox

I want to delete all files in the folder which names can not be found in listbox items. I assume i m missing a counter somewhere, but not really sure how to do this exactly.
Dim directoryName As String = "Folderimages"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*",SearchOption.TopDirectoryOnly)
For Each item In ListBox1.Items
Dim items As Object = ListBox1.Items
Dim itemText As String = ListBox1.GetItemText(items)
If Not deleteFile.Contains(itemText) Then
File.Delete(deleteFile)
End If
Next
Next
I think it might be a bit easier to split, the functionality you are creating here, just for easier usage aftewards
You can first have a function that gets all the items from your ListBox
Public Function GetItemsFromListBox( lbox as ListBox ) as IEnumerable(Of String)
return from item in lbox.Items _
select lbox.GetItemText( item )
End Function
And then have a function that retrieves all the files from a directory that are not inside that IEnumerable(Of String)
Public Function GetNonMatchingFiles( folder As String, nonMatchingItems As IEnumerable(Of String)) As IEnumerable(Of String)
Return Directory.GetFiles( folder ) _
.Where( Function(filename) not nonMatchingItems.Contains( Path.GetFileName( filename ), StringComparer.OrdinalIgnoreCase ) )
End Function
And then you can run through that result and delete the resultset. One thing to note would be that I compare the files with the filename only and not with the full path, if you don't want that, you should remove Path.GetFileName and just compare with filename, and that it will also look case insensitive
I didn't include the pattern (*.*) nor the searchoption as these are the defaults for that function anyhow
You could use Linq, so your test will become easier:
Dim directoryName As String = "Folderimages"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
If Not ListBox1.Items.Cast(Of String)().Any(Function(x) x = SearchString)) Then
File.Delete(deleteFile);
End If
Next
Did not try it, not sure if you need to cast the x as string.

Copying a file from a directory to another one

I have a an application which is supposed to copy a selected file whose directory is written in txtbox1 to a folder of director written in txtbox2 as follows :
code :
Dim sourcepath As String = TextBox1.Text
Dim DestPath As String = TextBox2.Text
CopyDirectory(sourcepath, DestPath)
Called sub:
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
This code copies all the files, not the specified one only. Can someone please tell me how to make this sub copy only the selected file not all the files in the folder?
You're taking the entire path as an argument (something like this: C:/someDirectory/filename.txt) and aren't comparing the filename to the other filenames in that directory.
Instead of using:
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
Try:
Dim sourceFileName = Path.GetFileName(sourcePath)
For Each filePath As String in Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim filename As String = Path.GetFileName(filePath)
If sourceFileName = filename
'Do your copy code here
End If
Next

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.

how to get value from spilt function in to string array

i want to use split function for splitting string into two parts.The question is how can i save the first part and second part into two different string array for further use?
The text i'm going to process is Name,filepath
Dim clientArr() as string
Dim FileArr() as string
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientArr = DataArr(0)
FileArr = DataArr(1)
loop
The error says that string cannot be convented into 1 D array
Thank you
It is the 21st Century and along with flying cars and robot dogs we have a easy way to keep 2 large sets of related data together in a single container, but able to be referenced individually:
Class myFileParts
public Property FileName As String
public Property FilePath As String
Public Sub New(fName as string, fPath as String)
FileName = fName
FilePath = fPath
End Sub
End Class
' a container to hold lots of these
Friend myFiles As New List(Of myFileParts)
' filling it up:
Dim TempLine As String
Dim myF As myFileParts
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
' create a file item
f = New myFileParts(DataArr(0),DataArr(1))
' add to container
myFiles.Add(f)
loop
to use one: (N is the index of the desired file info):
Dim thisFile As string = MyFiles(N).FileName
Dim thisPath As string = MyFiles(N).FilePath
to print them all:
For each f As myFileParts in myFiles
Console.WriteLine(String.Format("Path = {0}; Name = {1}",
f.FilePath, f.FileName)
Next f
The problem is that you declare ClientArr and FileArr as string arrays, which is what you want, but then you try to assign them a string value. DataArr(0) is a string value. You need to put that vcalue into one of the array elements in ClientArr. E.g. CleintArr(5) = DataArr(0).
If you knew the exact number of line in the file before the loop then you could declare the array size for CleintArr and FileArr. Then you would use an index that gets increments in the loop to set the proper array element.
But here is a better approach that will work without knowing the size of the file beforehand. This uses string collections to accumulate the clients and files, and then it converts them to an array once the file has been read.
Dim clientArr() As String
Dim FileArr() As String
Dim ClientList As New List(Of String)
Dim FileList As New List(Of String)
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientList.Add(DataArr(0))
FileList.Add(DataArr(1))
Loop
clientArr = ClientLIst.ToArray()
FileArr = FileList.ToArray()
Do you know how many lines are in the file before you start? If not, you could do something like this using the List class:
Dim clientPart As List(Of String) = New List(Of String)()
Dim filePart As List(Of String) = New List(Of String)()
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientPart.Add(DataArr(0))
filePart.Add(DataArr(1))
Loop
Dim clientPartStringArray As String() = clientPart.ToArray() 'If you really want an array
If you do, then you need to assign each split to an element of your clientArr and fileArr like:
Dim numLinesInFile As Integer 'If you know this value
Dim curIndex As Integer = 0
Dim clientArray(numLinesInFile) As String
Dim fileArray(numLinesInFile) As String
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientArray(curIndex) = DataArr(0)
fileArray(curIndex) = DataArr(1)
curIndex = curIndex + 1
Loop
Note the differences in your code in terms of:
We declare the arrays clientArray and fileArray with a specific size (you'll need to know this in advance - if you don't/can't know this consider using a collection like a List as previously alluded to)
On each iteration we assign the strings you get from the Split into a specific index of the array denoted by curIndex
We have to increment curIndex by 1 each time so that we write to empty slots in clientArray and fileArray...otherwise you'd just write to the same index (0) each time

Searching By File Extensions VB.NET [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
Hi all i have been trying to search a specified directory and all sub directories for all files that have the specified file extension. However the inbuilt command is useless as it errors up and dies if you dont have access to a directory. So here's what i have at the moment:
Private Function dirSearch(ByVal path As String, Optional ByVal searchpattern As String = ".exe") As String()
Dim di As New DirectoryInfo(path)
Dim fi As FileInfo
Dim filelist() As String
Dim i As Integer = 0
For Each fi In di.GetFiles
If System.IO.Path.GetExtension(fi.FullName).ToLower = searchpattern Then
filelist(i) = fi.FullName
i += 1
End If
Next
Return filelist
End Function
However i get an "System.NullReferenceException: Object reference not set to an instance of an object." when i try to access the data stored inside the filelist string array.
Any idea's on what im doing wrong?
You didn't instantiate the Dim filelist() As String array. Try di.GetFiles(searchPattern)
Dim files() as FileInfo = di.GetFiles(searchPattern)
Use static method Directory.GetFiles that returns an array string
Dim files = Directory.GetFiles(Path,searchPattern,searchOption)
Demo:
Dim files() As String
files = Directory.GetFiles(path, "*.exe", SearchOption.TopDirectoryOnly)
For Each FileName As String In files
Console.WriteLine(FileName)
Next
Recursive directory traversal:
Sub Main()
Dim path = "c:\jam"
Dim fileList As New List(Of String)
GetAllAccessibleFiles(path, fileList)
'Convert List<T> to string array if you want
Dim files As String() = fileList.ToArray
For Each s As String In fileList
Console.WriteLine(s)
Next
End Sub
Sub GetAllAccessibleFiles(path As String, filelist As List(Of String))
For Each file As String In Directory.GetFiles(path, "*.*")
filelist.Add(file)
Next
For Each dir As String In Directory.GetDirectories(path)
Try
GetAllAccessibleFiles(dir, filelist)
Catch ex As Exception
End Try
Next
End Sub
Use System.IO.Directory.EnumerateFiles method and pass SearchOption.AllDirectories in to traverse the tree using a specific search pattern. Here is an example:
foreach (var e in Directory.EnumerateFiles("C:\\windows", "*.dll", SearchOption.AllDirectories))
{
Console.WriteLine(e);
}