程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#創建並讀取ini文件

C#創建並讀取ini文件

編輯:C#入門知識

1,首先導入命名空間:using System.Runtime.InteropServices;
2,聲明API函數
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
3,創建ini文件
            WritePrivateProfileString("MyQQ", "ID", "798033502", @"C:\QQ.ini");
            WritePrivateProfileString("MyQQ", "PWD", "**********", @"C:\QQ.ini");
4,聲明API函數
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
5,讀取ini文件
           StringBuilder temp = new StringBuilder();
            GetPrivateProfileString("MyQQ", "ID", "賬號錯誤", temp, 255, @"C:\QQ.ini");
            string ID = temp.ToString();
            GetPrivateProfileString("MyQQ", "PWD", "讀取出錯", temp, 255, @"C:\QQ.ini");
            string PWD = temp.ToString();
            MessageBox.Show(ID + ":" + PWD);


6完整代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        private void button1_Click(object sender, EventArgs e)
        {
            WritePrivateProfileString("MyQQ", "ID", "798033502", @"C:\QQ.ini");
            WritePrivateProfileString("MyQQ", "PWD", "**********", @"C:\QQ.ini");
        }
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
       
        private void btnRead_Click(object sender, EventArgs e)
        {
            StringBuilder temp = new StringBuilder();  www.2cto.com
            GetPrivateProfileString("MyQQ", "ID", "賬號錯誤", temp, 255, @"C:\QQ.ini");
            string ID = temp.ToString();
            GetPrivateProfileString("MyQQ", "PWD", "讀取出錯", temp, 255, @"C:\QQ.ini");
            string PWD = temp.ToString();
            MessageBox.Show(ID + ":" + PWD);
        }
    }
}
作者:MyPC2010

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved