private static string AssocQueryString(ApplicationAssociation association) { uint appNameLength = 0; var result = WindowsApi.AssocQueryString(WindowsApi.AssocF.None, WindowsApi.AssocStr.FriendlyAppName, association.ProgId, null, null, ref appNameLength); if (new[] { 2147943555, 2147942402 }.Contains(result)) // No application is associated with the specified file for this operation OR The system cannot find the file specified { return(null); } if (result != 1) { throw new Win32Exception((int)result); } var buffer = new StringBuilder((int)appNameLength); var bufferLength = (uint)buffer.Capacity; result = WindowsApi.AssocQueryString(WindowsApi.AssocF.None, WindowsApi.AssocStr.FriendlyAppName, association.ProgId, null, buffer, ref bufferLength); if (result != 0) { throw new Win32Exception((int)result); } return(buffer.ToString()); }
private void btnDoFileAssociate_Click(object sender, EventArgs e) { try { using (FileAssociationManager mgr = new FileAssociationManager()) { foreach (object item in cListBoxFileExtension.CheckedItems) { using (ApplicationAssociation ext = mgr.RegisterFileAssociation(item.ToString())) { ext.DefaultIcon = new ApplicationIcon(Application.ExecutablePath); ext.ShellOpenCommand = Application.ExecutablePath; ext.Associated = true; } } } this.ShowMessage("已关联文件"); } catch (Exception ex) { this.ShowMessage(ex.Message); } }