For a Microsoft Visual C# .NET version of this
article, see
306222.
For a Microsoft Visual C++ .NET version of this
article, see
307387.
For a Microsoft Visual Basic 6.0 version of this
article, see
129797.
SUMMARY
This article demonstrates how to start the application that
is associated with a given document extension or file type without needing to
know the name or location of the associated application. For example, you can
start Arcade.bmp with the application that is associated with the .bmp file
extension, which is MSPaint.exe in most cases.
Requirements
- Microsoft Visual Basic .NET or Microsoft Visual Basic 2005
Specify The ProcessStartInfo information
You can use the
ProcessStartInfo structure of the .NET Framework
Process class to specify options when you start a process. This article
outlines how to use the file name option. Another member,
UseShellExecute, specifies that the process be started based on a file extension
or file type instead of the name of the executable (.exe). This property is set
to
true by default. It is set explicitly in this code for illustrative
purposes.
Dim fileName as String = "\eula.txt"
Dim sysFolder As String = _
Environment.GetFolderPath(Environment.SpecialFolder.System)
Dim pInfo As New ProcessStartInfo()
pInfo.FileName = sysFolder & fileName
pInfo.UseShellExecute = True
Start the application
This example opens a file named Eula.txt. The file is opened with
the application that is associated with the .txt file extension, which is
normally Notepad.exe. You can substitute any file name or type that has an
associated application.
Dim p As Process = Process.Start(pInfo)
Shortcut to start the application
Because
UseShellExecute is true by default for a process, it is not required that you use
ProcessStartInfo when you start a process. You can start the associated
application with a single line of code, as follows:
Dim p As Process = Process.Start("c:\winnt\system32\eula.txt")
Complete code sample
'How to Start a Process with a File Name
'Specify a file.
Dim fileName as String = "\eula.txt"
'Get the name of the system folder.
Dim sysFolder As String = _
Environment.GetFolderPath(Environment.SpecialFolder.System)
'Create a new ProcessStartInfo structure.
Dim pInfo As New ProcessStartInfo()
'Set the file name member of pinfo to Eula.txt in the system folder.
pInfo.FileName = sysFolder & fileName
'UseShellExecute is true by default. It is set here for illustration.
pInfo.UseShellExecute = True
'Start the process as specified in the process info structure.
Dim p As Process = Process.Start(pInfo)
Troubleshooting
It is possible that an individual computer may not have the
associated application installed, or the associations in the registry may not
be correct. It is best to wrap this code in a
try...catch block so that your application is alerted in the event of a
failure.