[vb.net]Check if a file exist in directory/subfolders and show its Explorer windows folder

  • Thread starter Thread starter Mattia Fanti
  • Start date Start date
M

Mattia Fanti

Guest
I'm using this code in order to check if file exist. Unfortunately It doesn't search also in subdirectory.
Code is:



Private Async Function ParentMethod() As Task
Dim filePath As String = Await Task.Run(
Function()

Return Directory.EnumerateFiles(My.Settings.Cartellasalvataggio, titolo & ".mp3",
SearchOption.AllDirectories).FirstOrDefault()
End Function)
If Not String.IsNullOrEmpty(filePath) Then
LinkLabel1.Text = "File exist already"
LinkLabel1.Visible = True
PictureBox7.Visible = True
Else
MsgBox("it doesn't exist")

End If

End Function


and the following class


Imports System.IO
Imports System.Runtime.InteropServices

Public Class NativeMethods
<DllImport("shell32.dll", SetLastError:=True)>
Private Shared Function SHOpenFolderAndSelectItems(
pidlFolder As IntPtr, cidl As UInteger,
<[In], MarshalAs(UnmanagedType.LPArray)> apidl As IntPtr(),
dwFlags As UInteger) As Integer
End Function

<DllImport("shell32.dll", SetLastError:=True)>
Private Shared Sub SHParseDisplayName(
<MarshalAs(UnmanagedType.LPWStr)> name As String,
bindingContext As IntPtr, <Out> ByRef pidl As IntPtr,
sfgaoIn As UInteger, <Out> ByRef psfgaoOut As UInteger)
End Sub

Public Shared Sub OpenFolderAndSelectFile(filePath As String)
Dim dirPath As String = Path.GetDirectoryName(filePath)
Dim fileName As String = Path.GetFileName(filePath)
OpenFolderAndSelectFile(dirPath, fileName)
End Sub

Public Shared Sub OpenFolderAndSelectFile(dirPath As String, fileName As String)
Dim nativeFolder As IntPtr
Dim psfgaoOut As UInteger
SHParseDisplayName(dirPath, IntPtr.Zero, nativeFolder, 0, psfgaoOut)

If nativeFolder = IntPtr.Zero Then
' Log error, can't find folder
Return
End If

Dim nativeFile As IntPtr
SHParseDisplayName(Path.Combine(dirPath, fileName),
IntPtr.Zero, nativeFile, 0, psfgaoOut)

Dim fileArray As IntPtr()
If nativeFile = IntPtr.Zero Then
' Open the folder without the file selected if we can't find the file
fileArray = New IntPtr(-1) {}
Else
fileArray = New IntPtr() {nativeFile}
End If

SHOpenFolderAndSelectItems(nativeFolder, CUInt(fileArray.Length), fileArray, 0)

Marshal.FreeCoTaskMem(nativeFolder)
If nativeFile <> IntPtr.Zero Then
Marshal.FreeCoTaskMem(nativeFile)
End If
End Sub
End Class



Then I am calling it with


Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked

NativeMethods.OpenFolderAndSelectFile((IO.Path.Combine(My.Settings.Cartellasalvataggio, titolo & ".mp3"))
End Sub


The problems I have are two:

- 1) The code doesn't search in subdirectory
- 2) The linklabel is updated just If I call the class ParentMethod two times.. Why?


Hope I explained the situation clearly.
Thanks

Continue reading...
 
Back
Top