C#配置檔案

海域發表於2024-08-17
  1. ini檔案讀取

  2. 獲取執行目錄

  3. App.config檔案讀取

  4. 系統資訊

ini檔案讀取

  1. ini檔案是個啥?

    .ini 檔案是Initialization File的縮寫,即初始化檔案,是 windows 的系統配置檔案所採用的儲存格式,統管 windows 的各項配置,一般使用者就用 windows 提供的各項圖形化管理介面就可實現相同的配置了。

  2. ini檔案以什麼格式儲存資料?

    [節點名稱]
    key1=value1
    key2=value2
    [其它節點]
    key1=value1
    key2=value2

  3. C# winform專案中如何讀寫ini檔案呢?

    藉助動態連結庫kernel32.dll

    kernel32.dll是Windows 9x/Me中非常重要的32位動態連結庫檔案,屬於核心級檔案。它控制著系統的記憶體管理、資料的輸入輸出操作和中斷處理,當Windows啟動時,kernel32.dll就駐留在記憶體中特定的防寫區域,使別的程式無法佔用這個記憶體區域。

  4. 在winform專案中使用一個動態連結庫的基本步驟?

    動態連結庫不需要引用,系統自帶。

    動態連結庫提供的功能比較多,說明動態連結庫中方法比較多。

    a. 先匯入動態連結庫,其實本質上是匯入的動態連結庫中某個方法。 [DllImport("kernel32.dll")]
    b. 就可以在C#程式碼中使用匯入的動態連結庫中的某個方法。

App.config檔案

  
  <?xml version="1.0" encoding="utf-8" ?>
     <configuration>
         <startup> 
             <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
         </startup>
     	<appSettings>
     		<add key="IniFilePath" value="C:\\test.ini"/>
     	</appSettings>
     </configuration>
     

IniFileHelper類

定義了一個 IniFileReader 類,其中使用 DllImport 引入了 Windows API 函式來讀取 ini 檔案中的值。

namespace _1.ini檔案讀取.Helpers
{
    public class IniFileHelper
    {
        private static string filePath = ConfigurationManager.AppSettings["IniFilePath"].ToString();

        #region 匯入動態連結庫中方法
        [DllImport("kernel32.dll")]
        /// <summary>
        /// 獲取值
        /// </summary>
        /// <param name="section">段落名</param>
        /// <param name="key">鍵名</param>
        /// <param name="defval">讀取異常是的預設值</param>
        /// <param name="retval">鍵名所對應的的值,沒有找到返回空值</param>
        /// <param name="size">返回值允許的大小</param>
        /// <param name="filepath">ini檔案的完整路徑</param>
        /// <returns></returns>
        private static extern int GetPrivateProfileString(string section, string key, string defval, StringBuilder retval, int size, string filepath);

        /// <summary>
        /// 寫入
        /// </summary>
        /// <param name="section">需要寫入的段落名</param>
        /// <param name="key">需要寫入的鍵名</param>
        /// <param name="val">寫入值</param>
        /// <param name="filepath">ini檔案的完整路徑</param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern int WritePrivateProfileString(string section, string key, string val, string filepath);
        #endregion

           
        /// <summary>
        /// 讀取Ini檔案
        /// </summary>
        /// <param name="section">節點</param>
        /// <param name="key">鍵</param>
        /// <returns>值</returns>
        public static string ReadIniFile(string section, string key)
        {
            StringBuilder sb = new StringBuilder(1024);
            GetPrivateProfileString(section, key, "", sb, 1024, filePath);
            return sb.ToString();
        }

        /// <summary>
        /// 寫入Ini檔案
        /// </summary>
        /// <param name="section">節點</param>
        /// <param name="key">鍵</param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static void WriteIniFile(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, filePath);
        }
    }
}

窗體設計


//儲存
private void btnSave_Click(object sender, EventArgs e)
{
    IniFileHelper.WriteIniFile("裝置規格", "裝置名稱", txtSBMC.Text);
    IniFileHelper.WriteIniFile("裝置規格", "處理器", txtCLQ.Text);
    IniFileHelper.WriteIniFile("裝置規格", "機帶RAM", txtJDRAM.Text);
    IniFileHelper.WriteIniFile("裝置規格", "裝置ID", txtSBID.Text);
    IniFileHelper.WriteIniFile("裝置規格", "產品ID", txtCPID.Text);
    IniFileHelper.WriteIniFile("裝置規格", "系統型別", txtXTLX.Text);
    IniFileHelper.WriteIniFile("裝置規格", "筆和觸控", txtBHCK.Text);

    IniFileHelper.WriteIniFile("Windows規格", "版本", txtBB.Text);
    IniFileHelper.WriteIniFile("Windows規格", "版本號", txtBBH.Text);
    IniFileHelper.WriteIniFile("Windows規格", "安裝日期", txtAZRQ.Text);
    IniFileHelper.WriteIniFile("Windows規格", "作業系統版本", txtCZXTBB.Text);
    IniFileHelper.WriteIniFile("Windows規格", "體驗", txtTY.Text);

    MessageBox.Show("儲存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

//讀取
private void btnRead_Click(object sender, EventArgs e)
{
    ReadIniFile();

    MessageBox.Show("讀取成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}


private void ReadIniFile()
{
    txtSBMC.Text = IniFileHelper.ReadIniFile("裝置規格", "裝置名稱");
    txtCLQ.Text = IniFileHelper.ReadIniFile("裝置規格", "處理器");
    txtJDRAM.Text = IniFileHelper.ReadIniFile("裝置規格", "機帶RAM");
    txtSBID.Text = IniFileHelper.ReadIniFile("裝置規格", "裝置ID");
    txtCPID.Text = IniFileHelper.ReadIniFile("裝置規格", "產品ID");
    txtXTLX.Text = IniFileHelper.ReadIniFile("裝置規格", "系統型別");
    txtBHCK.Text = IniFileHelper.ReadIniFile("裝置規格", "筆和觸控");

    txtBB.Text = IniFileHelper.ReadIniFile("Windows規格", "版本");
    txtBBH.Text = IniFileHelper.ReadIniFile("Windows規格", "版本號");
    txtAZRQ.Text = IniFileHelper.ReadIniFile("Windows規格", "安裝日期");
    txtCZXTBB.Text = IniFileHelper.ReadIniFile("Windows規格", "作業系統版本");
    txtTY.Text = IniFileHelper.ReadIniFile("Windows規格", "體驗");
}

1723901179779

1723901240022

獲取執行目錄

獲取專案的執行路徑

 
 private void button1_Click(object sender, EventArgs e)
 {
     // 獲取專案執行路徑:bin/Debug
     Console.WriteLine(Environment.CurrentDirectory);// 當前目錄
     Console.WriteLine(Directory.GetCurrentDirectory()); // 當前目錄
     Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); // 基目錄
     Console.WriteLine(Application.StartupPath);//啟動路徑
     Console.WriteLine(Application.ExecutablePath);// 執行路徑,帶可執行檔案 .exe
     Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
 }

使用程序物件開啟一個其它的軟體


private void button2_Click(object sender, EventArgs e)
{
    // Process程序,Start()方法可以啟動系統中其他軟體。
    //Process.Start("C:\\Users\\dongshuhua\\Desktop\\C#軟體開發\\15\\配置檔案\\1.ini檔案讀取\\bin\\Debug\\1.ini檔案讀取.exe");

    //Process.Start(@"C:\Program Files\Tencent\QQNT\QQ.exe");

    Process.Start(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe");
}

動態設定影像


private void button3_Click(object sender, EventArgs e)
{
    string path = Environment.CurrentDirectory;
    string fullPath = Path.Combine(path, "..\\..\\","Images\\bd.png");
    pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
    pictureBox2.Image = Image.FromFile(fullPath);
}

App.config檔案讀取

配置檔案App.config


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
	<!--連線字串,用來連線資料庫用的。各種資料庫都可以使用連線字串-->
	<connectionStrings>
		<add name="SQLServer" connectionString="server=.;database=dong;uid=sa;pwd=123456;"/>
	</connectionStrings>
	<!--應用程式設定, 鍵值對-->
	<appSettings>
		<add key="Name" value="張三"/>
		<add key="Age" value="20"/>
		<add key="Sex" value="男"/>
	</appSettings>
</configuration>

連線字串(Connection String)主要用於建立與資料庫的連線。它包含了連線資料庫所需的各種引數資訊,例如資料庫伺服器的名稱、資料庫的名稱、認證方式(使用者名稱和密碼)、連線超時等。

AppConfigHelper.cs


namespace _3.App.config檔案讀取.Helpers
{
    public static class AppConfigHelper
    {
        private static Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        //ConfigurationManager 是.NET 框架中的一個類,用於訪問應用程式的配置資訊。它提供了靜態方法和屬性來獲取 App.config 或 Web.config 檔案中的配置設定,例如 AppSettings 節和 ConnectionStrings 節中的資訊。
        public static string Get(string key, bool isConnectionString = false)
        {
            string result = null;
            if (isConnectionString)
            {
                foreach (ConnectionStringSettings item in config.ConnectionStrings.ConnectionStrings)
                {
                    if(item.Name== key)
                    {
                        result = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                        break;
                    }
                }
            }
            else
            {
                foreach (KeyValueConfigurationElement item in config.AppSettings.Settings)
                {
                    if (item.Key == key)
                    {
                        result= ConfigurationManager.AppSettings[key];
                        break;
                    }
                }
            }
            return result;
            /*try
            {
                return isConnectionString ? ConfigurationManager.ConnectionStrings[key].ConnectionString : ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return null;
            }*/
        }

        
        public static void Add(string key, string value, bool isConnectionString = false)
        {
            if (isConnectionString)
            {
                if (Get(key, true) == null)
                {
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings(key, value)
                    );
                }
                else
                {
                    config.ConnectionStrings.ConnectionStrings.Remove(key);
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings(key, value)
                    );
                }
            }
            else
            {
                if (Get(key) == null) config.AppSettings.Settings.Add(key, value);
                else
                {
                    config.AppSettings.Settings.Remove(key);
                    config.AppSettings.Settings.Add(key, value);
                }
            }

            config.Save();
        }

        
        public static void Remove(string key)
        {
            config.AppSettings.Settings.Remove(key);
        }
        

        public static void Clear()
        {
            config.AppSettings.Settings.Clear();
        }
    }
}

窗體設計

1723903837411

呼叫類裡面的相應方法。

系統資訊

窗體設計

1723904292963

//System.Timers.Timer timer;
public Form1()
{
    InitializeComponent();

    //timer.Elapsed += Timer_Elapsed;

}

/*private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    throw new NotImplementedException();
}*/

Microsoft.VisualBasic.Devices.Computer myInfo = new Microsoft.VisualBasic.Devices.Computer();

private void Form1_Load(object sender, EventArgs e)
{
    lblCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    timer1.Interval = 1000;  // 間隔時間,單位:毫秒
    timer1.Tick += Timer1_Tick;

    lblComputeName.Text = Environment.MachineName + "    " + myInfo.Name;
    // \n
    //lblNewLine.Text = "HELLO" + Environment.NewLine + "World!";
    lblNewLine.Text = "HELLO\nWorld!";

    //TimeSpan time = TimeSpan.FromMilliseconds(Environment.TickCount);
    TimeSpan time = TimeSpan.FromMilliseconds(myInfo.Clock.TickCount);
    string timeStr = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
    lblSystemStartTime.Text = timeStr;

    lblDirectory.Text = Environment.CurrentDirectory;

    // Operate System作業系統。
    lblVersion.Text = Environment.OSVersion.ToString();

    Console.WriteLine(Environment.OSVersion.VersionString);
    Console.WriteLine(Environment.OSVersion.Platform);
    Console.WriteLine(Environment.OSVersion.Version);
    Console.WriteLine(Environment.OSVersion.ServicePack); // 補丁

    lblCUPCount2.Text = Environment.ProcessorCount.ToString();

    lblSystemType.Text = Environment.Is64BitOperatingSystem ? "64位" : "32位";

    //獲取實體記憶體總量
    lblMemoryTotal.Text = (myInfo.Info.TotalPhysicalMemory / 1024 / 1024 / 1024D).ToString("0.0") + " GB";
    //獲取可用實體記憶體總量
    lblMemoryAvailable.Text = (myInfo.Info.AvailablePhysicalMemory / 1024 / 1024 / 1024D).ToString("0.0") + " GB";

    Console.WriteLine(myInfo.Screen.DeviceName);

}

private void Timer1_Tick(object sender, EventArgs e)
{
    lblCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}

private void button1_Click(object sender, EventArgs e)
{
    timer1.Enabled = true;  // 啟動定時器
    //timer1.Start();  // 啟動定時器, 會執行定時器Tick事件  
}

private void button2_Click(object sender, EventArgs e)
{
    timer1.Enabled = false;  // 禁用定時器

    /*if (timer1.Enabled)
    {
        timer1.Stop();
    }*/

}

private void button3_Click(object sender, EventArgs e)
{
    Application.Exit(); // 應用程式退出

    //this.Close();// 專案主窗體關閉也可以讓應用程式退出

    Environment.Exit(0); // 應用程式執行環境退出

}