Hello all,
So lets say I have a folder and in it I have 3 files.
How would I go about Identifying the biggest(in bytes) and moving it somewhere else on the hard drive, say C:\BiggestFile.jpg?
Thanks in advance!
Shredder2794
Hello all,
So lets say I have a folder and in it I have 3 files.
How would I go about Identifying the biggest(in bytes) and moving it somewhere else on the hard drive, say C:\BiggestFile.jpg?
Thanks in advance!
Shredder2794
I would do it like this:
Imports System.IO
Imports System.Linq
Module Module1
Function GetLargestFile(ByVal strDir As String, ByVal strPattern As String) As String
Return _
(From strFile In Directory.GetFiles(strDir, strPattern)
Let FileInfo = New FileInfo(strFile)
Order By FileInfo.Length Descending
Select FileInfo.FullName).First()
End Function
Sub Main()
Console.WriteLine(GetLargestFile("c:\myPath\", "*.jpg"))
End Sub
End Module
I'm no expert at VB and am having some trouble with this.
Can you elaborate some more?
That method uses Directory.GetFiles() to get all of the files from a directory.
For each file it finds, it creates a new FileInfo object.
The .Length property tells the file size.
It then sorts the FileInfo objects by size in descending order.
It then returns the name of the first one in that list.
All of that is wrapped into a function called GetLargestFile() that takes the name of the directory to look in and the types of files to find.
How would I go about doing this recursively for all the files in the current directory, and all the files in all the child directories?
Sorry for all the noob questions.
Assuming you have permission to all of the subdirectories, you could add something simple like this:
Sub Main()
Dim strRoot As String = "c:\myPath\"
Dim lst_strDirs As List(Of String) = Directory.GetDirectories(strRoot, "*.*", SearchOption.AllDirectories).ToList()
lst_strDirs.ForEach(Sub(strDir) Console.WriteLine(GetLargestFile(strDir, "*.jpg")))
End Sub
BUT you should change the .First() in the GetLargestFile() to .FirstOrDefault() if there could be empty directories in the path.
See this article in in MSDN that (although in C#) explains a recursive method and a non-recursive method if you don't have read permission to all subdirectories.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.