C# 获取txt文件(.NET)的标准应用程序

C# 获取txt文件(.NET)的标准应用程序,c#,.net,windows,process,C#,.net,Windows,Process,在我的应用程序中,我想打开一个没有.txt扩展名的文本文件。有没有办法在.NET(C#)中获取.txt文件的标准应用程序?当然我可以使用“记事本”,但可能有一些人(像我一样)更喜欢另一个(他们的标准)编辑器 编辑: 注册表项“[HKEY\U CLASSES\U ROOT]\txtfile\shell\open\command”引用了记事本,但这不是我用于txt文件的标准应用程序。如何获取我当前的.txt标准应用程序?直接打开.txt文件即可 Process.Start("MyFile.txt"

在我的应用程序中,我想打开一个没有.txt扩展名的文本文件。有没有办法在.NET(C#)中获取.txt文件的标准应用程序?当然我可以使用“记事本”,但可能有一些人(像我一样)更喜欢另一个(他们的标准)编辑器


编辑:


注册表项“[HKEY\U CLASSES\U ROOT]\txtfile\shell\open\command”引用了记事本,但这不是我用于txt文件的标准应用程序。如何获取我当前的.txt标准应用程序?

直接打开.txt文件即可

Process.Start("MyFile.txt");
它应该使用首选的文本编辑器自动打开

编辑:

哎呀,我没看到它没有.txt扩展名。可能需要在注册表中检查首选编辑器

编辑:


它就在我的电脑(Windows 7)上:HKEY_CLASSES\u ROOT\textfile\shell\open\command

绝对最好的选择是使用,传递
SEE_MASK\u CLASSNAME
标志,打开这个文件,就像它是
“.txt”
。这是唯一支持基于DDE和基于拖放的文件打开机制的方法

但是,如果您想自己做(例如,在部分信任的情况下运行,并且无法p/invoke
ShellExecuteEx
),下面是如何做的:

还有另一个间接层次。你必须先查一下

HKCR\.txt

从该键中读取默认值,称之为txtkey

然后检查

HKCR\txtkey\shell\open\command


还有一个函数可以为您执行此操作:

据我所知,您必须通过p/Invoke访问它,但最干净的方法可能是使用您关心的扩展名创建一个临时文件,并调用该临时文件。然后,您可以使用该可执行文件打开您关心的文件。

我的代码,其中包括一些检查,以防止出现一些常见错误。。。希望有帮助:-)

使用系统;
使用系统诊断;
使用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”))
{
if(executablePath.ToLower().EndsWith(“openwith.exe”))
{
return null;//“OpenWith.exe”是未知扩展名的windows 8或更高版本的默认值。我不希望将其作为关联文件
}
返回可执行路径;
}
返回可执行路径;
}
[DllImport(“Shlwapi.dll”,SetLastError=true,CharSet=CharSet.Auto)]
静态外部uint AssocQueryString(AssocF标志、AssocStr str、字符串pszAssoc、字符串pszExtra、[Out]StringBuilder pszOut、[In][Out]ref uint pcchOut);
私有静态字符串文件扩展信息(AssocStr AssocStr、字符串doctype、字符串动词)
{
uint pcchOut=0;
AssocQueryString(AssocF.Verify、assocStr、doctype、verb、null、ref-pcchOut);
Assert(pcchOut!=0);
如果(pcchOut==0)
{
返回“”;
}
StringBuilder pszOut=新的StringBuilder((int)pcchOut);
AssocQueryString(AssocF.Verify、assocStr、doctype、动词、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
}
}
}

请参阅问题:“没有.txt扩展名的文件”谢谢,但该文件没有.txt扩展名。想象一个.bat文件。在这种情况下,“Process.Start”将启动批处理文件。--已关闭,但该副本无法解决我的问题。。因为在该注册表项下我只找到“%SystemRoot%\system32\NOTEPAD.EXE%1”。。这不是我的标准应用程序。txt@iDog:同意。我把我的改成了写字板,注册表项是doe
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
        }



    }
}