在C#中,如果你想要获取当前执行程序的文件名(不包括路径),你可以使用System.Reflection.Assembly
类中的GetExecutingAssembly()
方法来获取当前执行的程序集(Assembly),然后通过ManifestModule
属性获取主模块,最后使用Name
属性来获取文件名(包括扩展名)。但是,Name
属性实际上返回的是程序集的简单名称,通常不包括路径或文件扩展名。为了获取完整的文件名,你应该使用Location
属性,并从中提取文件名部分。
以下是获取当前执行程序文件名的代码示例:
using System;
using Microsoft.Win32;
class Program
{
static void Main(string[] args)
{
// 获取当前执行的程序集
Assembly executingAssembly = Assembly.GetExecutingAssembly();
// 获取程序集的位置(包括路径和文件名)
string assemblyLocation = executingAssembly.Location;
// 提取文件名(包括扩展名)
string fileName = Path.GetFileName(assemblyLocation);
// 定义要关联的文件扩展名和应用程序路径
string[] extensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };
string applicationPath = fileName ;
string fileType = "Photo Browser";
string fileTypeDescription = "Photo Browser";
// 遍历每个文件扩展名并创建注册表条目
foreach (string ext in extensions)
{
// 关联文件扩展名到文件类型
using (RegistryKey extKey = Registry.ClassesRoot.CreateSubKey(ext))
{
extKey.SetValue("", fileType);
}
// 如果文件类型条目不存在,则创建并设置它
using (RegistryKey fileTypeKey = Registry.ClassesRoot.CreateSubKey(fileType))
{
if (fileTypeKey.SubKeyCount == 0)
{
fileTypeKey.SetValue("", fileTypeDescription);
// 设置打开文件的命令
using (RegistryKey openKey = fileTypeKey.CreateSubKey("shell\\open\\command"))
{
openKey.SetValue("", applicationPath + " \"%1\"");
}
// 可选:设置文件类型的图标
using (RegistryKey iconKey = fileTypeKey.CreateSubKey("DefaultIcon"))
{
iconKey.SetValue("", applicationPath + ",0");
}
}
}
}
// 提示用户操作已完成
Console.WriteLine("文件关联已成功添加到注册表中。你可能需要注销并重新登录或重启计算机以使更改生效。");
}
}