Check if part of file name exists in a path using .net - vb.net

I would like to check in my weapplication if a file exists in a path provided. File name can be anything eg:pic.jpg, pic.txt,pic1.txt,pic2.jpg etc.
I need to check if "pic" name exists in the path.Only check if 'pic' exists or pic+anything+.jpg or pic.anything.txt exists using vb.net.
Please help.

You'll want to check the File.Exists method. Don't forget, this only work for finding files on the server, not the client. Finding a file on the client side is a totaly different mather.

You can get the list of files in the given directory and then check the filenames to see if the fragment of text you're looking for is in any of them. Assuming you want to include the extension in the test and you don't care if it is upper or lower case:
Function FilenameFragmentExists(srcDir As String, fragment As String) As Boolean
Dim files() As String = IO.Directory.GetFiles(srcDir)
Dim found As Boolean = False
For i = 0 To files.Length - 1
If IO.Path.GetFileName(files(i)).IndexOf(fragment, StringComparison.OrdinalIgnoreCase) > -1 Then
found = True
Exit For
End If
Next
Return found
End Function
Or you can do it in one line with LINQ, and if you are using .NET framework >=4 then you can use .EnumerateFiles instead of .GetFiles, which has a chance of being faster:
Function FilenameFragmentExists(srcDir As String, fragment As String) As Boolean
Return IO.Directory.EnumerateFiles(srcDir).Any(Function(f) IO.Path.GetFileName(f).IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0)
End Function

You should use Directory.GetFiles(path, pattern) to check if it returns some files corresponding to your pattern. For example
Dim files = Directory.GetFiles("C:\temp", "*.jpg")
if files.Length > 0 Then
Console.WriteLine("Directory contains " + files.Length + " with the required pattern")
Else
Console.WriteLine("Directory doesn't contain any file with the required pattern")
End if
In the second parameter you could pass any kind of pattern following the usual wildcard rules used for directory listing

Related

Using the contains() method

Hello I am trying trying to use the contains method to see if a list-block (which exclusively consists of filepaths) 'contains' a certain string. It is supposed to remove the respective entry (in a for loop) if the string is contained in the filepath.
Dim index As Integer = findNumFiles("Archer", 6) '//returns number of files in archer directory
Dim iString As String = "Archer"
For i = 0 To index
If Lookup.Items(index).contains(iString) Then
removeFromList(Lookup, index) '//passes "Lookup" as a ListBlock name and removes the index number
End If
Next
a sample filepath would be
"Z:\Movies and TV\Archer\Season 6\1.mp4"
edit: I forgot to mention that it does not work. I tested the command with a list entry simply named "archer" and if the iString is = to "archer", that list entry is removed. It seems the fact that I'm attempting to use the contains method on a filepath is the problem but I'm not sure.
Thanks for any insight!
Use Instr function to check if the string present or not,
I am not sure about what "Lookup.Items" .
Use 'i'in for loop instead of index
Hope below code will help you
Sub test1()
Dim index As Integer
index = findNumFiles("Archer", 6)
'//returns number of files in archer directory
Dim iString As String
iString = "Archer"
For i = 0 To index
If InStr(1,Lookup.Items(i), iString, 1) > 0 Then
' removeFromList(Lookup, index) '//passes "Lookup" as a ListBlock name and removes the index number
End If
Next
End Sub

For each using linq how to use else

i have code that is checking for specific files and then if condition is fulfilled its going in to stats.matching.... I am using this for each linq:
For Each file As String In From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where ftpFile.Contains(currentReportName)
Select file1
Stats.MatchingFiles.Add(file)
Next
The question is how to implement else here.
So you want to fill another collection with files that don't contain the word.
Dim matching = From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where ftpFile.Contains(currentReportName)
Dim mismatching = From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where Not ftpFile.Contains(currentReportName)
For Each file As String In matching
Stats.MatchingFiles.Add(file)
Next
For Each file As String In mismatching
Stats.MismatchingFiles.Add(file)
Next
That is the simple solution, you could also use Except which is more efficient:
Dim mismatching = Stats.FoundFiles.Except(matching)
I think in your case original For Each loop with If... Else will be simple enough approach
And loop a Stats.FoundFile only once
For Each file As String In Stats.FoundFiles
Dim ftpFile As String = Utils.ToLowerWithoutSpaces(file)
If ftpFile.Contains(currentReportName) = True Then
Stats.MatchingFiles.Add(file)
Else
Stats.MismatchingFiles.Add(file)
End If
Next
Or if you are fan of LINQ and must to use it, then you can play with Aggregate extension method
Stats.FoundFiles.Aggregate(String.Empty,
Function(seed, file)
If Utils.ToLowerWithoutSpaces(file).Contains(file) Then
Stats.MatchingFiles.Add(file)
Else
Stats.MismatchingFiles.Add(file)
End If
Return String.Empty
End Function)

VBNET Reading a specific column on a line in a text file

I have saved written a text file and it currently reads:
"first","surname","pass"
I want to read the password column so the 3rd one and define that as a variable. Its basically for a login, if pass in text file matches the entered pass (from user).
I have searched for about an hour now and no luck. Could someone guide me to a correct path.
Thanks.
Simple example of reading a small file line by line and splitting each one into fields:
' get the values from the user somehow:
Dim first As String = "James"
Dim surname As String = "Bond"
Dim pass As String = "007"
Dim validated As Boolean = False ' assume wrong until proven otherwise
' check the file:
Dim fileName As String = "c:\some folder\path\somefile.txt"
Dim lines As New List(Of String)(System.IO.File.ReadAllLines(fileName))
For Each line As String In lines
Dim values() As String = line.Split(",")
If values.Length = 3 Then
If values(0).Trim(Chr(34)) = first AndAlso
values(1).Trim(Chr(34)) = surname AndAlso
values(2).Trim(Chr(34)) = pass Then
validated = True
Exit For
End If
End If
Next
' check the result
If validated Then
MessageBox.Show("Login Successful!")
Else
MessageBox.Show("Login Failed!")
End If
If this is a CSV file, as seems to be the case, then the easiest way to read it will be with the TextFieldParser class. The MSDN already provides an excellent example for how to use it to read a CSV file, so I won't bother reproducing it here.

How can I check if filename contains a portion of a string in vb.net

I have a userform in 2008 vb express edition. A part number is created from user input via a concat string. I want to then check if a certain portion of the part number exists in the existing file names in a directory. Below is a more detailed explanation.
This is my code for creating a part number from the user input on the form.
L_PartNo.Text = String.Concat(CB_Type.Text, CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")", mount, T_Qty.Text, weep, serv)
I then have the following code to tell the user if the configuration (part no) they just created exists
L_Found.Visible = True
If File.Exists("Z:\Cut Sheets\TCS Products\BLANK OUT SIGN\" & (L_PartNo.Text) & ".pdf") Then
L_Found.Text = "This configuration exists"
Else
L_Found.Text = "This configuration does NOT exist"
End If
This is where I need help. The part no will look like this BX002(30x30)A1SS I want to compare 002(30x30) (just this part of the file name) to all the files in one directory. I want a yes or no answer to the existance and not a list of all matching files. The code below is everything I've tried, not all at the same time.
Dim b As Boolean
b = L_PartNo.Text.Contains(NewFace)
Dim NewFace As String = String.Concat(CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")")
Dim NewFace = L_PartNo.Text.Substring(2, 10)
If filename.Contains(NewFace) Then
lNewFace.Visible = False
Else
lNewFace.Visible = True
End If
The code below was a translation from the answer in C# but it does not work either
Dim contains As Boolean = Directory.EnumerateFiles(path).Any(Function(f) [String].Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase))
Here's an example of how you can do it without the fancy LINQ and Lambda which seem to be confusing you:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.Contains(phrase) Then
Return True
End If
Next
Return False
End Function
Or, if you need it to be case insensitive:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
You would call the method like this:
lNewFace.Visible = FileMatches(path, "*.pdf", NewFace)
Try this:
lNewFace.Visible = IO.Directory.GetFiles(path, "*.pdf").Where(Function(file) file. _
Substring(2, 10) = NewFace).FirstOrDefault Is Nothing
Consider that the substring function will throw an exception if its arguments exceed the length of the string it is parsing

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]