/// <summary> /// For a file extension (with leading period) and a verb (or null for default /// verb), returns the (full?) path to the executable file that is assigned to /// that extension/verb. Returns null if an error occurs. /// </summary> public static string GetExecutablePath(string extension, string verb) { int capacity = 270; attempt: // we may need to retry with a different (larger) value for "capacity" StringBuilder buffer = new StringBuilder(capacity); // the buffer that will hold the result int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.EXECUTABLE, extension, verb, buffer, ref capacity); switch (hresult) { case HRESULT.S_OK: return(buffer.ToString()); // success; return the path // failure; buffer was too small case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary (AssocQueryString // assigns it). it should work if we try again. goto attempt; // failure. the default case will catch all, but I'm explicitly // calling out the two failure codes I know about in case we need // them someday. case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: return(null); } }
/// <summary> /// Gets the friendly type string for an extension. /// </summary> public static string GetTypeNameForExtension(string extension) { if (extension != null) { extension = extension.Trim(); } int capacity = 270; attempt: StringBuilder builder = new StringBuilder(capacity); int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.FRIENDLYDOCNAME, extension, null, builder, ref capacity); switch (hresult) { case HRESULT.S_OK: return(builder.ToString()); case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary. try again goto attempt; case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: break; } if (extension == null || extension == string.Empty) { return("Unknown"); } else { return(extension.TrimStart('.').ToUpper(CultureInfo.InvariantCulture) + " File"); } }