我正在学习C#编程并构建一个简单的ClickOnce应用程序。我知道这个问题以前曾被问过,我试图从那里得到指导,但是由于没人提供完整的代码(所有使用语句等),所以出现了一些错误。因此,我遇到的帖子,由于我需要至少50个我不是初学者的声望,因此我无法对其中任何一个发表评论以要求获得完整的帖子。
这是我的简单程序代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32; // for registry
namespace MyRegApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// add to start up registry
// The path to the key where Windows looks for startup applications
RegistryKey add = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
add.SetValue("MyApp", "\"" + Application.ExecutablePath.ToString() + "\"");
Console.WriteLine("Progam installed successfully, please press any key to exit");
Console.ReadKey();
}
}
}
但是在Visual Studio 2017中,Application.ExecutablePath中的Application出现红色下划线,并且出现错误“ Application名称在当前上下文中不存在”或类似的错误(附有屏幕截图)。
请告知我是否需要将注册表位放入其他方法或其他文件中,或者如何使它起作用。
========编辑========
修复了编译问题后,我现在遇到了另一个问题。尝试写入注册表时出现权限错误。我已经咨询了其他一些职位,但没有发现任何类似的内容。下面是我当前的代码版本,其中包含用于授予自己所有必要权限的代码段,对您的帮助将不胜感激。
namespace MyRegApp
{
class Program
{
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
Console.WriteLine("Hello World!");
// add to start up registry
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
RegistrySecurity rs = new RegistrySecurity();
rs = key.GetAccessControl();
string currentUserStr = Environment.UserDomainName + "\\" + Environment.UserName;
rs.AddAccessRule(new RegistryAccessRule(currentUserStr, RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.FullControl, AccessControlType.Allow));
try
{
key.SetValue("MyRegApp", "\"" + Assembly.GetExecutingAssembly().CodeBase.ToString() + "\"");
}
catch (SecurityException e) {
Console.WriteLine("Security Exception:\n\n{0}", e.Message);
}
Console.WriteLine("Progam installed successfully, please press any key to exit");
Console.ReadKey();
}
}
}
答案 0 :(得分:1)
Application.ExecutablePath
需要引用System.Windows.Forms
命名空间。
如果需要控制台应用程序的可执行路径,请尝试使用Assembly.GetExecutingAssembly().CodeBase
。您需要引用System.Reflection
命名空间。