"Запустить процесс" файл без расширения в vb.net

мы уже знаем, как System.Diagnostics.Process.Start("C:filename.png") работает, но что если имя файла не заканчивается с расширением? Как я могу запустить имя файла без расширения в имени файла, используя программу по умолчанию, связанную с расширением PNG?

что-то типа:

openFile("C:filename","PNG")

1 ответов


VB.Net DllImport на AssocQueryString(). см. MSDN функция AssocQueryString

<DllImport("Shlwapi.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Public Shared Function AssocQueryString(flags As AssocFlags, str As AssocStr, 
                       pszAssoc As String, pszExtra As String, <Out> pszOut As System.Text.StringBuilder, 
                       <[In]> <Out> ByRef pcchOut As UInteger) As UInteger
End Function

и его перечисления: см. MSDN перечисление ASSOCF, ASSOCSTR перечисление

<Flags> _
Public Enum AssocFlags
    None = &H0                     'No option selected
    Init_NoRemapCLSID = &H1        'Instructs the interface methods not to map CLSID values to ProgID values.
    Init_ByExeName = &H2           'THe pszAssoc parameter is an executable file name: the root key for search is set to the executable file's ProgID.
    Open_ByExeName = &H2           'Alias for Init_ByExeName
    Init_DefaultToStar = &H4       'If the value is not found under the root key, it should retrieve the comparable value from the * subkey.
    Init_DefaultToFolder = &H8     'If the value is not found under the root key, it should retrieve the comparable value from the Folder subkey.
    NoUserSettings = &H10          'Only the HKEY_CLASSES_ROOT should be searched, HKEY_CURRENT_USER should be ignored.
    NoTruncate = &H20              'The return string should not be truncated. Return an error value and the required size for the complete string.
    Verify = &H40                  'Instructs to verify that data is accurate. This setting allows to read data from the user's hard disk for verification.
    RemapRunDll = &H80             'Instructs to ignore Rundll.exe and return information about its target.
    NoFixUps = &H100               'Instructs not to fix errors in the registry, such as the friendly name of a function not matching the one found in the .exe file.
    IgnoreBaseClass = &H200        'Specifies that the BaseClass value should be ignored.
    IgnoreUnknown = &H400          'Windows 7:   "Unknown" ProgID should be ignored; instead, fail.
    InitFixedProgid = &H800        'Windows 8:   The supp. ProgID should be mapped using the sys defaults, rather than the current user defaults.
    IsProtocol = &H1000            'Windows 8:   The value is a protocol, should be mapped using the current user defaults.
    InitForFile = &H2000           'Windows 8.1: The ProgID corresponds with a file extension based association. Use together with InitFixedProgid.
End Enum

Public Enum AssocStr
    Command = 1,                   'A command string associated with a Shell verb (=> Open, Edit, Print, New).
    Executable,                    'An executable from a Shell verb command string. Not all associations have executables.
    FriendlyDocName,               'The friendly name of a document type.    (Microsoft Office 2016 Document)
    FriendlyAppName,               'The friendly name of an executable file. (Microsoft Office Word)
    NoOpen,                        'Ignore the information associated with the open subkey.
    ShellNewValue,                 'Look under the ShellNew subkey.
    DDECommand,                    'A template for DDE commands.
    DDEIfExec,                     'The DDE command to use to create a process.
    DDEApplication,                'The application name in a DDE broadcast.
    DDETopic,                      'The topic name in a DDE broadcast.
    Infotip,                       'The InfoTip registry value. Returns an info tip for an item from which to create an info tip, such as when hovering the cursor over a file name. 
    Quicktip,                      'Corresponds to the QuickTip registry value. Similar to InfoTip, but more suitable for network transport.
    TileInfo,                      'Corresponds to the TileInfo registry value. Similar to InfoTip, for a file type in a window that is in tile view.
    ContentType,                   'Describes a general type of MIME file association, such as image and bmp, to make general assumptions about a specific file type.
    DefaultIcon,                   'Returns the path to the default icon for this association. Positive numbers: index of the dll's resource table, Negative numbers: resource ID.
    ShellExtension,                'If a Shell extension is associated, use this to get the CLSID of the Shell extension object, passing the string of the IID as the pwszExtra parameter.
    DropTarget,                    'For a verb invoked through COM and the IDropTarget interface, use this flag to get the IDropTarget object's CLSID. The verb is specified in the pwszExtra parameter.
    DelegateExecute,               'For a verb invoked through COM and the IExecuteCommand interface, use this flag to get the IExecuteCommand object's CLSID. This CLSID is registered in the verb's command subkey as the DelegateExecute entry. The verb is specified in the pwszExtra parameter.
    SupportedURIProtocols,         'Windows 8   
    ProgID,                        'The ProgID provided by the app associated with the file type or URI scheme. This if configured by users in their default program settings.
    AppID,                         'The AppUserModelID of the app associated with the file type or URI scheme. This is configured by users in their default program settings.
    AppPublisher,                  'The publisher of the app associated with the file type or URI scheme. This is configured by users in their default program settings.
    AppIconReference,              'The icon reference of the app associated with the file type or URI scheme. This is configured by users in their default program settings.
    Max                            'The maximum defined ASSOCSTR value, used for validation purposes.
End Enum

это возможная реализация:

'This is a helper function, so you don't need to pass flags
Public Function FileExtentionInfo(AssociationType As AssocStr, Extension As String) As String
    If (Extension.Length <= 1) OrElse Not Extension.StartsWith(".") Then
        Return String.Empty
    Else
        Dim flags As AssocFlags = AssocFlags.NoTruncate Or AssocFlags.RemapRunDll
        Return ShellExtensionInfo(True, AssociationType, flags, Extension)
    End If
End Function

'This is the "Worker" function
Private Function ShellExtensionInfo(Verify As Boolean, AssociationType As AssocStr, flags As AssocFlags, Extension As String) As String
    Dim pcchOut As UInteger = 0
    flags = flags Or (If(Verify, AssocFlags.Verify, AssocFlags.IgnoreUnknown))
    AssocQueryString(flags, AssociationType, Extension, Nothing, Nothing, pcchOut)

    If pcchOut = 0 Then
        Return String.Empty
    Else
        Dim pszOut As New StringBuilder(CType(pcchOut, Integer))
        AssocQueryString(flags, AssociationType, Extension, Nothing, pszOut, pcchOut)
        Return pszOut.ToString()
    End If
End Function

чтобы получить результат, просто вызовите вспомогательную функцию, спросив, какая информация или ассоциация (AssocStr) вы хотите.

Dim Executable As String = FileExtentionInfo(AssocStr.Executable, "FileExtension")

так, например вы называете это так:

Dim Executable As String = FileExtentionInfo(AssocStr.Executable, ".docx")

для меня результат такой:

C:\Program файлы\Microsoft Office\Office16\WINWORD.EXE

не все расширения имеют исполняемую ассоциацию. Некоторые расширения файлов могут быть сопоставлены с инструментом системный апплет, который начинается с Rundll32.exe.
В этом случае, использование AssocStr.Executable в качестве параметра может не возвращать жизнеспособный результат.
Например, если программное обеспечение для редактирования изображений не установлено, исполняемый файл для .jpg или .png расширения может вернуться:

C:\Program файлы (x86)\Windows Photo Viewer\PhotoViewer.dll файлы

в этом случае использовать AssocStr.Command в качестве параметра для получения связанных командной строки, которая затем может быть передана System.Diagnostics.Process.Start(). Таким образом, в том же случае результат будет:

C:\Windows\System32\rundll32.exe "C:\Program файлы (x86)\Windows фото Viewer\PhotoViewer.файл DLL", ImageView_Fullscreen %1

здесь %1 представляет имя открываемого файла.
Этот параметр можно передать с помощью ProcessStartInfo.Доводы собственность.