如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
---------------------------------
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Win32; using System.IO; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // Class1.test(); // Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("軟體自啟動"); String LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"); MessageBox.Show(Environment.CurrentDirectory+"\n"+LogPath); //Class1.test(); } private void Form1_Load(object sender, EventArgs e) { AutoStart(); } private void AutoStart(bool isAuto = true, bool showinfo = true) { try { if (isAuto == true) { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.SetValue("應用名稱", Application.ExecutablePath); R_run.Close(); R_local.Close(); } else { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.DeleteValue("應用名稱", false); R_run.Close(); R_local.Close(); } } // if (showinfo) // MessageBox.Show("您需要管理員權限修改", "提示"); // Console.WriteLine("您需要管理員權限修改"); catch (Exception ex) { String LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"); if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath); if (!File.Exists(LogPath + "\\log.txt")) File.Create(LogPath + "\\log.txt").Close(); string fileName = LogPath + "\\log.txt"; string content = DateTime.Now.ToLocalTime() + " 0001_" + "您需要管理員權限修改" + "\n" + ex.StackTrace + "\r\n"; Logger(fileName, content); } } public static void disPlay(string path) { MessageBox.Show(path); } public void Logger(string fileName, string content) { using (StreamWriter sw = new StreamWriter(fileName, true)) { sw.Write(content); sw.Close(); sw.Dispose(); } } } }

發現沒?開機自動啟動后
Environment.CurrentDirectory 發生了變更,
這樣在在我們程式中原本如果使用相對路徑進行處理的,就找不見相應的檔案了,
怎么處理?
方法1:
在程式初始化的時候改變下當前路徑
public Form1()
{
InitializeComponent();
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
方法2:添加環境變數 , 計算行--屬性--高級系統設定--環境變數--系統變數里面設定.
---------------------------------------------------------------------
如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/168964.html
標籤:.NET技术
上一篇:C# 用IrisSkin4.dll美化你的WinForm
下一篇:C# 軟體版本號
