C# 将我的程序添加到startup,现在可以';我不能访问我程序的文件
我使用RegistryKey将我的程序添加到启动中,如下所示:C# 将我的程序添加到startup,现在可以';我不能访问我程序的文件,c#,visual-studio,registrykey,C#,Visual Studio,Registrykey,我使用RegistryKey将我的程序添加到启动中,如下所示: private async void baslatKontrol_CheckedChanged(object sender, EventArgs e) { RegistryKey rk = Registry.CurrentUser.OpenSubKey ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run&qu
private async void baslatKontrol_CheckedChanged(object sender, EventArgs e)
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
string yol = Path.Combine(Environment.CurrentDirectory, "Asistanim.exe");
if (baslatKontrol.Checked)
{
rk.SetValue(yol, Application.ExecutablePath);
veri.Baslat = true;
await JsonVeriden(veri);
}
else
{
rk.DeleteValue(yol, false);
veri.Baslat = false;
await JsonVeriden(veri);
}
}
问题是,;在我的程序目录中有一个名为“Veri.json”的文件,但每次我重新启动计算机并运行程序时,它都会给我一个例外:“在C:\Windows\system32\Veri.json中找不到Veri.json”
我的程序正在其他地方运行,我希望我的程序使用它在当前目录中创建的文件。如何执行此操作?您需要使用应用程序文件夹,或者例如,使用启动exe路径,而不是windows中默认的或从控制台命令行点获取的环境当前文件夹:
var path = Application.ExecutablePath;
要在从IDE或从安装路径运行可执行文件之间保持良好的一致性,可以使用:
/// <summary>
/// Indicate generated executable bin directory name.
/// </summary>
static public string BinDirectoryName
=> "Bin";
/// <summary>
/// Indicate generated executable bin\debug directory combination.
/// </summary>
static public string DebugDirectoryCombination
=> Path.Combine(BinDirectoryName, "Debug");
/// <summary>
/// Indicate generated executable bin\release directory combination.
/// </summary>
static public string ReleaseDirectoryCombination
=> Path.Combine(BinDirectoryName, "Release");
/// <summary>
/// Indicate the application executable file name.
/// </summary>
static public string ApplicationExeFileName
=> Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
/// <summary>
/// Indicate the root folder path of the application.
/// </summary>
static public string RootFolderPath
=> Directory.GetParent(Path.GetDirectoryName(Application.ExecutablePath
.Replace(DebugDirectoryCombination, BinDirectoryName)
.Replace(ReleaseDirectoryCombination, BinDirectoryName))).FullName;
您当然可以插入任何子文件夹
如果json文件与可执行文件位于同一目录中,您可以使用这些东西来改进应用程序的二分法。问题在于您假设当前目录是exe所在的目录,并使用相对路径来读取json文件。当exe由另一个进程调用/被另一个进程调用时,您必须考虑以下情况。另一个选项是在开始时获取exe的路径,并在每个地方使用完整路径。@Sinatr不理解第二个选项。
var yol=path.Combine(exeDir,“Asistanim.exe”)
,其中exeDir
指向exe的路径(从上面链接的答案)。没有设置当前目录。@Sinatr谢谢。你能把这个做成一个答案吗?我肯定这个问题已经被问过了,但是找不到重复的。
var pathJSON = Path.Combine(RootFolderPath, "Veri.json");