如何根据扩展名获取文件类型信息?(不是哑剧)用c#
如何获得基于扩展名的常规文件类型描述,就像Explorer那样?所以不是MIME,而是最终用户看到的信息,比如 .doc=Microsoft Office Word 97-2003文档 .zip=zip文件 .avi=视频文件如何根据扩展名获取文件类型信息?(不是哑剧)用c#,c#,file,mime,file-type,C#,File,Mime,File Type,如何获得基于扩展名的常规文件类型描述,就像Explorer那样?所以不是MIME,而是最终用户看到的信息,比如 .doc=Microsoft Office Word 97-2003文档 .zip=zip文件 .avi=视频文件 我如何才能获得似乎可用的“次要”信息,我猜这不是基于扩展的。就像在“视频文件”中一样,它可以告诉你电影的“长度”,或者在文档文件中,它有多少页。。等等……直接从注册表中读取类似的内容通常是个坏主意(请参阅所有相关信息)。在这种特殊情况下,您需要的API是AssocQuer
我如何才能获得似乎可用的“次要”信息,我猜这不是基于扩展的。就像在“视频文件”中一样,它可以告诉你电影的“长度”,或者在文档文件中,它有多少页。。等等……直接从注册表中读取类似的内容通常是个坏主意(请参阅所有相关信息)。在这种特殊情况下,您需要的API是
AssocQueryString
Inshlwapi.h
这里是C++代码:
TCHAR buf[1024];
DWORD sz = sizeof(buf) / sizeof(TCHAR);
AssocQueryString(ASSOCF_INIT_DEFAULTTOSTAR, ASSOCSTR_FRIENDLYDOCNAME, L".sql", NULL, buf, &sz);
您可以从C#通过C++/CLI公开一个友好的.NET API来使用它;或者直接通过电话联系。谢谢,丹,好的。。这回答了我的第一个问题。遗憾的是,这不是第二次。注意:并不是所有的东西都会打印。。 归功于
使用系统;
使用System.Runtime.InteropServices;
使用系统文本;
使用系统诊断;
命名空间Windows窗体应用程序1
{
静态类程序
{
[DllImport(“Shlwapi.dll”,SetLastError=true,CharSet=CharSet.Auto)]
静态外部uint AssocQueryString(AssocF标志、AssocStr str、字符串pszAssoc、字符串pszExtra、[Out]StringBuilder pszOut、[In][Out]ref uint pcchOut);
///
///应用程序的主要入口点。
///
[状态线程]
静态void Main()
{
Debug.WriteLine(fileextensioninfo(AssocStr.Command,.doc”),“Command”);
Debug.WriteLine(fileextensioninfo(AssocStr.DDEApplication,.doc”),“DDEApplication”);
Debug.WriteLine(fileextensioninfo(AssocStr.DDEIfExec,“.doc”),“DDEIfExec”);
Debug.WriteLine(fileextensioninfo(AssocStr.DDETopic,.doc),“DDETopic”);
Debug.WriteLine(fileextensioninfo(AssocStr.Executable,.doc”),“Executable”);
Debug.WriteLine(fileextensioninfo(AssocStr.FriendlyAppName,“.doc”),“FriendlyAppName”);
Debug.WriteLine(fileextensioninfo(AssocStr.FriendlyDocName,“.doc”),“FriendlyDocName”);
Debug.WriteLine(fileextensioninfo(AssocStr.NoOpen,.doc”),“NoOpen”);
Debug.WriteLine(fileextensioninfo(AssocStr.ShellNewValue,.doc”),“ShellNewValue”);
//应用程序:WinWord
//DDEIfExec:nﻴ߾
//主题:系统
//可执行文件:C:\ProgramFiles(x86)\Microsoft Office\Office12\WINWORD.EXE
//FriendlyAppName:Microsoft Office Word
//FriendlyDocName:MicrosoftOfficeWord 97-2003文档
}
公共静态字符串文件扩展信息(AssocStr AssocStr,字符串doctype)
{
uint pcchOut=0;
AssocQueryString(AssocF.Verify、assocStr、doctype、null、null、ref pcchOut);
StringBuilder pszOut=新的StringBuilder((int)pcchOut);
AssocQueryString(AssocF.Verify、assocStr、doctype、null、pszOut、ref pcchOut);
返回pszOut.ToString();
}
[旗帜]
公共普查协会
{
Init_NoRemapCLSID=0x1,
Init_ByExeName=0x2,
打开\u ByExeName=0x2,
Init_DefaultToStar=0x4,
Init_DefaultToFolder=0x8,
NoUserSettings=0x10,
NoTruncate=0x20,
验证=0x40,
RemapRunDll=0x80,
NoFixUps=0x100,
IgnoreBaseClass=0x200
}
公共普查协会
{
命令=1,
可执行文件,
FriendlyDocName,
友好的应用程序名,
努蓬,
ShellNewValue,
DDE命令,
DDEIfExec,
应用程序,
DDETopic
}
}
}
对于XP中未知的文件类型,有一些额外的if。。
当与FriendlyDocName以外的任何东西一起使用时,可能不会给出正确的结果,但仅作为一个示例:
public static string FileExtentionInfo(AssocStr assocStr, string doctype)
{
if ((doctype.Length <= 1) || !doctype.StartsWith(".")) return "";
uint pcchOut = 0;
AssocQueryString(AssocF.Verify, assocStr, doctype, null, null, ref pcchOut);
if (pcchOut == 0) return (doctype.Trim('.').ToUpper() + " File");
StringBuilder pszOut = new StringBuilder((int)pcchOut);
AssocQueryString(AssocF.Verify, assocStr, doctype, null, pszOut, ref pcchOut);
return pszOut.ToString();
}
publicstaticstringfileextensioninfo(assocstrassocstr,stringdoctype)
{
如果((doctype.Length我的代码包含检查以防止出现一些常见错误…希望有帮助:-)
使用系统;
使用系统诊断;
使用System.IO;
使用System.Runtime.InteropServices;
使用系统文本;
命名空间HQ.Util.Unmanaged
{
///
///用法:string executablePath=FileAssociation.GetExecutFileAssociatedToExtension(路径扩展,“打开”);
///
公共静态类文件关联
{
///
///
///
///
///
///如果未找到,则返回null
公共静态字符串GetExecFileAssociatedToExtension(字符串扩展,字符串谓词=null)
{
如果(分机[0]!='。)
{
ext=“.”+ext;
}
string executablePath=fileextensioninfo(AssocStr.Executable,ext,verb);//仅适用于“open”verb
if(string.IsNullOrEmpty(executablePath))
{
executablePath=FileExtensionInfo(AssocStr.Command,ext,verb);//查找除“open”之外的任何其他动词的命令都是必需的
//只提取路径
如果(!string.IsNullOrEmpty(executablePath)&&executablePath.Length>1)
{
如果(可执行路径[0]='''''')
{
executablePath=executablePath.Split(“\”)[1];
}
else if(可执行路径[0]='\'')
{
executablePath=executablePath.Split('\'')[1];
}
}
}
//确保在Windows 8或更高版本中不返回与OpenWith.exe关联的默认可执行文件
如果(!string.IsNullOrEmpty(executablePath)&&File.Exists(executablePath)&&
!executablePath.ToLower().EndsWith(“.dll”
public static string FileExtentionInfo(AssocStr assocStr, string doctype)
{
if ((doctype.Length <= 1) || !doctype.StartsWith(".")) return "";
uint pcchOut = 0;
AssocQueryString(AssocF.Verify, assocStr, doctype, null, null, ref pcchOut);
if (pcchOut == 0) return (doctype.Trim('.').ToUpper() + " File");
StringBuilder pszOut = new StringBuilder((int)pcchOut);
AssocQueryString(AssocF.Verify, assocStr, doctype, null, pszOut, ref pcchOut);
return pszOut.ToString();
}
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace HQ.Util.Unmanaged
{
/// <summary>
/// Usage: string executablePath = FileAssociation.GetExecFileAssociatedToExtension(pathExtension, "open");
/// </summary>
public static class FileAssociation
{
/// <summary>
///
/// </summary>
/// <param name="ext"></param>
/// <param name="verb"></param>
/// <returns>Return null if not found</returns>
public static string GetExecFileAssociatedToExtension(string ext, string verb = null)
{
if (ext[0] != '.')
{
ext = "." + ext;
}
string executablePath = FileExtentionInfo(AssocStr.Executable, ext, verb); // Will only work for 'open' verb
if (string.IsNullOrEmpty(executablePath))
{
executablePath = FileExtentionInfo(AssocStr.Command, ext, verb); // required to find command of any other verb than 'open'
// Extract only the path
if (!string.IsNullOrEmpty(executablePath) && executablePath.Length > 1)
{
if (executablePath[0] == '"')
{
executablePath = executablePath.Split('\"')[1];
}
else if (executablePath[0] == '\'')
{
executablePath = executablePath.Split('\'')[1];
}
}
}
// Ensure to not return the default OpenWith.exe associated executable in Windows 8 or higher
if (!string.IsNullOrEmpty(executablePath) && File.Exists(executablePath) &&
!executablePath.ToLower().EndsWith(".dll"))
{
if (executablePath.ToLower().EndsWith("openwith.exe"))
{
return null; // 'OpenWith.exe' is th windows 8 or higher default for unknown extensions. I don't want to have it as associted file
}
return executablePath;
}
return executablePath;
}
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, [In][Out] ref uint pcchOut);
private static string FileExtentionInfo(AssocStr assocStr, string doctype, string verb)
{
uint pcchOut = 0;
AssocQueryString(AssocF.Verify, assocStr, doctype, verb, null, ref pcchOut);
Debug.Assert(pcchOut != 0);
if (pcchOut == 0)
{
return "";
}
StringBuilder pszOut = new StringBuilder((int)pcchOut);
AssocQueryString(AssocF.Verify, assocStr, doctype, verb, pszOut, ref pcchOut);
return pszOut.ToString();
}
[Flags]
public enum AssocF
{
Init_NoRemapCLSID = 0x1,
Init_ByExeName = 0x2,
Open_ByExeName = 0x2,
Init_DefaultToStar = 0x4,
Init_DefaultToFolder = 0x8,
NoUserSettings = 0x10,
NoTruncate = 0x20,
Verify = 0x40,
RemapRunDll = 0x80,
NoFixUps = 0x100,
IgnoreBaseClass = 0x200
}
public enum AssocStr
{
Command = 1,
Executable,
FriendlyDocName,
FriendlyAppName,
NoOpen,
ShellNewValue,
DDECommand,
DDEIfExec,
DDEApplication,
DDETopic
}
}
}
private void Form1_Load(object sender, EventArgs e) {
getSometypes();
}
private void getSometypes()
{
System.Diagnostics.Debug.WriteLine(getFileType(".txt"));
System.Diagnostics.Debug.WriteLine(getFileType(".doc"));
System.Diagnostics.Debug.WriteLine(getFileType(".xlsx"));
}
private string getFileType(object ext)
{
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
string tempPath = System.IO.Path.GetTempPath();
string tempFile = "";
tempFile = tempPath + "tmp" + ext;
System.IO.File.WriteAllText(tempFile, "");
var f = fso.GetFile(tempFile);
string t = f.Type;
f.Delete();
return t;
}
Textdokument
Microsoft Word 97–2003-dokument
Microsoft Excel-kalkylblad