Search code examples
c#vb.netvisual-studio-2013frameworkswin32-process

Win32 Exception while running my VB application on different devices


Good evening, Please I'm doing an application in VB that opens a file. Here's my code:

Public Class Form1

Private Sub Form1_click(sender As Object, e As EventArgs) Handles MyClass.Click
    Dim myProc As New System.Diagnostics.Process()
    myProc.StartInfo.FileName = "E:\ex.txt" 'The file in a flash drive
    myProc.Start()
    Me.Hide()
End Sub
End Class

The thing is that the program works very well for me (I have the latest version of .NET Framework), but, when I try it in another office, it gives that exception "System.ComponentModel.Win32Exception 0x80004005 : The system cannot find the file specified". Please, how can I get it working in another device (x86 or x64, with or without the latest version of .net framework) ? Thank you.

UPDATE 1 : I added the exception code : 0x80004005

UPDATE 2 : I just edited the path in my code, because the old one was just to explain my question, but it seemed that it was a very bad idea, so, I just modified the path to the real path in my projet (E:\ex.txt)


Solution

  • Drive letters are not always the same on all machines especially with removable storage.
    System.IO.DriveInfo.GetDrives can be used to get information on all logical drives and find the file:

    For Each driveInfo In System.IO.DriveInfo.GetDrives ' loop all logical drives on the computer 
    
        If driveInfo.DriveType = System.IO.DriveType.Removable Then ' optional check if removable storage device 
    
            Dim fileInfos = driveInfo.RootDirectory.GetFiles("ex.txt") ' search for driveLetter:\ex.txt 
    
            If fileInfos.Length > 0 Then
    
                System.Diagnostics.Process.Start(fileInfos(0).FullName) ' start the file 
    
                Exit For  ' optional to leave the For loop 
    
            End If
        End If
    Next