Using VB.Net
Get a file name without using for next from the directory
Dim filefound = Directory.GetFiles("C:\", "1.txt")
For Each inwardfile In filefound
Dim strFilename As String = Path.GetFileName(inwardfile)
Next
The above code is working fine, but i dont want to use for loop because i will always get one file at a time not the list of files also i am searching with filename not like "*.txt"
So How to modify the code, Any one can assist.
Your question is inconsistent which makes it very unclear. Do you want a file name or a collection of them? If you want filename not like "*.txt" then why use "1.txt" for GetFiles?
This will answer the title question How to get a filename without using for next. For this, assume a directory full of ".json" files. Some are named cs###.json (e.g. cs001.json) some are named vb###.json and many others.
Path would work to allow you to examine parts of the filename, but DirectoryInfo will provide access to some of that info via FileInfo objects. This uses EnumerateFiles to be able to filter out unwanted files so they are not even returned to your code/array variable.
Dim dix As New DirectoryInfo("C:\Temp\Json")
Get the json files which DO NOT start with CS. This will return an array of FileInfo objects in case you need to do further exclusions:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.StartsWith("cs") = False).
ToArray()
Get the json files which ARE "*1.json" and DO NOT start with "cs". In this case, the last Select method will cause an array of filenames to be returned:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.EndsWith("1.json") AndAlso
f.Name.StartsWith("cs") = False).
Select(Function(q) q.Name).
ToArray()
Change the Select to 'Function(q) q.FullName` if you want the full path name. These should come close to whatever you are really looking for.
Related
How can I add the file creation date filter for files created today and tomorrow?
This part don't work and I need to add files created today and tomorrow:
.Where(Function(file) New FileInfo(file).CreationTime.Date = DateTime.Today.Date)
Dim pdfList As String() = _
Directory.GetFiles(sourceDir, "*.PDF").Where(Function(file) New
FileInfo(file).CreationTime.Date = _
DateTime.Today.Date)
For Each f As String In pdfList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length + 1)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, _
fName), True)
Next
Dim folder As New DirectoryInfo(sourceFolderPath)
Dim files = folder.EnumerateFiles("*.pdf")
.Where(Function(fi) fi.CreationTime.Date = Date.Today)
For Each file In files
file.CopyTo(Path.Combine(backupFolderPath, file.Name))
Next
There are a few things to note here:
We are creating a DirectoryInfo and using it to get FileInfo objects. Given that you were creating a FileInfo for each file anyway, it's silly not to do this. That FileInfo object gives you the creation time, file name without the folder path and a method to copy the file.
We are calling EnumerateFiles rather than GetFiles. The latter returns an array containing all files, but we don't want all files in this case. If you're going to filter then enumeration is better, because it gets each file one by one, processes a file and discards it before getting the next. That's more efficient. In this case, we don't even call ToArray or ToList, so the files aren't actually retrieved until the loop and then they are retrieved and processed one by one.
The is no point using Date.Today.Date. Today has already had the time zeroed. Internally, Date.Today uses Date.Now.Date.
I have a few files that pending on factors may require an alternate-variation to be used. The selection of the right file starts at standard windows directory C:\Drawings in my case, So I know that we can add items to the windows backbround context menu as follows:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\txtfile\shell\mymenu]
#="test123"
[HKEY_CLASSES_ROOT\txtfile\shell\mymenu\command]
#="%SystemRoot%\\system32\\NOTEPAD.EXE %1"
However (and im not sure even if this is possible) i would like to get the name of the file that was cliked and use it in my vb.net application for example a textbox wich displays that files name.
dose anybody know if i can do this? and how?
First you'll have to get the command line arguments, which can be done in a few different ways but I prefer to use Environment.GetCommandLineArgs():
Dim Arguments() As String = Environment.GetCommandLineArgs()
Then you must check that there's actually an argument to read. The very first argument (index 0) is always the path to your application, therefore we must check that it contains at least two arguments to be sure that there is also one passed to your app.
If Arguments.Length >= 2 Then
Finally you just get the path to the file from the second argument, and call IO.Path.GetFileName() on that:
Dim FilePath As String = Arguments(1) 'Second argument has index 1.
Dim FileName As String = IO.Path.GetFileName(FilePath)
If you don't want the file's path at all you can just go ahead and do:
Dim FileName As String = IO.Path.GetFileName(Arguments(1))
Full code:
Dim Arguments() As String = Environment.GetCommandLineArgs()
If Arguments.Length >= 2 Then
Dim FilePath As String = Arguments(1) 'Second argument has index 1.
Dim FileName As String = IO.Path.GetFileName(FilePath)
'Do your stuff here.
End If
I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()
I need to find an Excel file. However, the extension of the file I"m looking for could be .xls or .xlsx. I was considering using FileExists but I can't use a wildcard with that. Here's my attempt at using GetFiles, however, the .xls* part of my code does not work. I've never used GetFiles before, can anyone give me some guidance on what I'm doing wrong?
Dim InputFormPath As String = "W:\TOM\ERIC\NET Dev\"
Dim wbNameXLSInputForm As String = StatVar.xlApp.Sheets("New Calculator Input").Range("D15").Text & ".xls*"
Dim XLSInputForm As String = wbNameXLSInputForm
Dim dirs As String() = Directory.GetFiles(InputFormPath, wbNameXLSInputForm)
If dirs.Length <> 0 Then
'do something
End If
Take a look at this documentation. It says: The following list shows the behavior of different lengths for the searchPattern parameter: "*.abc" returns files having an extension of.abc,.abcd,.abcde,.abcdef, and so on.
Let's say I have a directory 'C:\Test' with three files in it:
A23456789.txt
A1.txt
G 5.txt
And I run this command:
Dim FileArr = Directory.GetFiles("C:\Test", "*1.txt", SearchOption.AllDirectories)
All three files are returned.
I understand that this is by design and .NET searches the 8.3 short file names as well.
But is there any way to override this and search the actual file names only?
Surely, in this day and age there must be a function to do this. Or do I have to write my own?
I would like the search function to have the same behavior as the Windows Explorer for consistency.
I think the best approach would be to remove the filter from GetFiles and filter it out with LINQ, where you have a little more control:
Dim FileArr = Directory.GetFiles("C:\Test", "*.txt", SearchOption.AllDirectories)
Dim filtered = From f In FileArr Where Path.GetFileName(f).EndsWith("1.txt")
Or some equivalent.
This uses LINQ:
Dim FileArr = IO.Directory.GetFiles("C:\Test", "*.txt", SearchOption.AllDirectories). _
Where(Function(s) s Like "*1.txt")