1.

Solve : VB get filename or edit text?

Answer»

hi guys,

i am USING this code to grab file names:

My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.CurrentDirectory, FileIO.SearchOption _
.SearchTopLevelOnly, "*.gif*", "*.jpg*", "*.jpeg*", "*.jif*")

when i load this into a list box it appears as c:\docu~\visua~\filename.ext

what im trying to get is just the filename or filename.ext, is there a command to get this or can i somehow edit the string?

any help will be great avoid using the My namespace if you can.

I really have absolutely no idea why it would return the short name.
the main issue here is that you are being given a collection of strings rather then a more helpful array of files.

you could use Directory.GetCurrentDirectory.Getfiles() to RETRIEVE files, but you can only specify a single file mask.

Not to fear, however- it's rather easy to slap together a small FUNCTION that does what the My Namespace function does but giving back FileInfo Objects rather then short path names:

Code: [Select]Sub Main()
Dim useMasks As String = "*.jpg|*.jpeg|*.jif|*.gif"

Dim filesgot As ArrayList
Dim loopfile As FileInfo
filesgot = GetFilesDirect(New DirectoryInfo(Directory.GetCurrentDirectory), useMasks)
For Each loopfile In filesgot
Console.WriteLine(loopfile.FullName)


Next
Console.ReadKey()
End Sub

Private Function GetFilesDirect(ByVal StartFolder As DirectoryInfo, ByVal Filemasks As String, _
Optional ByVal SearchOption As SearchOption = SearchOption.TopDirectoryOnly) As ArrayList
Dim returnArray As ArrayList = New ArrayList
Dim filemaskarr() As String = Filemasks.Split("|")
Dim I As Long
For Each fInfo As FileInfo In StartFolder.GetFiles("*.*", SearchOption.TopDirectoryOnly)
For I = 0 To filemaskarr.Length - 1
If fInfo.Name Like filemaskarr(I) Then
returnArray.Add(fInfo)
Exit For
End If

Next I
Next fInfo
Return returnArray
End Function

The "Main" Function here does essentially what you want- enumerates the matching files in the currentDirectory. Just copy the function to your code (in a blank area, and not inside another function, obviously) and call it in a similar fashion instead of using the My namespace.

Now, you ask "how does this help? I want just the filename!"

WELL, as you can see in my Main() routine, I use the "FullName" property of the FileInfo Class. In your case, you could use the "Name" property to get the Filename.ext, or the "Extension" property to get the file extension. using both together and some string manipulation, it's rather easy to get just the basename:
(Loopfile in the following is a "FileInfo" Object)
Code: [Select]loopfile.Name.Substring(1, loopfile.Name.Length - loopfile.Extension.Length - 1)
Yay it works!

sorry for late reply was too AMUSED by my 90% program haha.

Thanks BC



Discussion

No Comment Found