C#中读写INI配置文件

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace ATESmartWheelBleTest
{
    class Config
    {
        [DllImport("kernel32")]//返回0表示失败,非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        static string iniPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\" + "ini.ini";

        public static void InitIniFile()
        {
            if(!File.Exists(iniPath))
            {
                //写初始值
                WritePrivateProfileString("Wheel", "Circumference", "1", iniPath);
            }
        }

        public static void WriteWheelCircu(string data)
        {
            WritePrivateProfileString("Wheel", "Circumference", data, iniPath);
        }

        public static double GetWheelCircu()
        {
            try
            {
                StringBuilder retTemp = new StringBuilder(20);
                GetPrivateProfileString("Wheel", "Circumference", "", retTemp, 1024, iniPath);                
                return double.Parse(retTemp.ToString());
            }
            catch
            {
                return 0;
            }

        
        }

    }
}

转:http://kb.cnblogs.com/page/43446/
在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于Xml的兴起,现在的配置文件大都是以xml文档来存储。比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介绍Remoting中提到的配置文件,都是xml的格式。

传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的。ini文件其实就是一个文本文件,它有固定的格式,节Section的名字用[]括起来,然后换行说明key的值:
[section]
key=value

如数据库服务器配置文件:

DBServer.ini

[Server]
Name=localhost
[DB]
Name=NorthWind
[User]
Name=sa

在C#中,对配置文件的读写是通过API函数来完成的,代码很简单:

using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace PubOp
{
    
public class OperateIniFile
    
{
        
API函数声明

        
读Ini文件

        
写Ini文件
    }

}


简单说明以下方法WriteIniData()和ReadIniData()的参数。

Section参数、Key参数和IniFilePath不用再说,Value参数表明key的值,而这里的NoText对应API函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的Value时,就用NoText的值来代替。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace PrintIncrease
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        [DllImport("kernel32")]//返回0表示失败,非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);
        string strIniPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)+ "\\" + "INI.ini";
        private void btnSourceFile_Click(object sender, EventArgs e)
        {
            chlstFile.Items.Clear();
            // 设置根在桌面SpecialFolder
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;
            // 设置当前选择的路径
            folderBrowserDialog1.SelectedPath = "d:\\";
            // 允许在对话框中包括一个新建目录的按钮
            folderBrowserDialog1.ShowNewFolderButton = true;
            // 设置对话框的说明信息
            folderBrowserDialog1.Description = "请选择需转化程序目录";
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            { 
                // 在此添加代码,选择的路径为 folderBrowserDialog1.SelectedPath
                txtSourcePath.Text = folderBrowserDialog1.SelectedPath;
               
            }
            if (txtSourcePath.Text.Length > 2)
            {
                ImportSourceFile(txtSourcePath.Text);
            }
          

        }
        private void ImportSourceFile(string filePath)
        {
            try
            {

                    string strPathFileName;
                    string strFileName;
                    
                    string[] fileName = Directory.GetFiles(filePath);
                    int fileCount = Directory.GetFiles(filePath).Length;
                    for (int i = 0; i < fileCount; i++)
                    {
                        strPathFileName = fileName[i];                      
                        strFileName = strPathFileName.Substring(strPathFileName.LastIndexOf("\\")+1);
                        if (strFileName.LastIndexOf(".TXT") > -1)
                        {
                            chlstFile.Items.Add(strFileName);
                        }
                        if (strFileName.LastIndexOf(".txt") > -1)
                        {
                            chlstFile.Items.Add(strFileName);
                        }   
                
                    }
            }
            catch (System.Exception ex)
            {
                lblMsg.Text = ex.Message;
            }

        }
        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            // 设置根在桌面SpecialFolder
            folderBrowserDialog2.RootFolder = Environment.SpecialFolder.Desktop;
            // 设置当前选择的路径
            folderBrowserDialog2.SelectedPath = "d:\\";
            // 允许在对话框中包括一个新建目录的按钮
            folderBrowserDialog2.ShowNewFolderButton = true;
            // 设置对话框的说明信息
            folderBrowserDialog2.Description = "请选择需转化程序目录";
            if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
            {
                // 在此添加代码,选择的路径为 folderBrowserDialog1.SelectedPath
                txtSavePath.Text = folderBrowserDialog2.SelectedPath;
            }

        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            int iFileCout = chlstFile.Items.Count;
            int iSelectCout=0;
            for (int i = 0; i < iFileCout; i++)
            {
                if (chlstFile.GetItemChecked(i) == true)
                {
                    iSelectCout++;
                }
            }
            if (iSelectCout <= 0)
            {
                lblMsg.Text = "没有要处理的程序文件!";
                return;
            }
            string strSourceDir = txtSourcePath.Text;
            string strSaveDir = txtSavePath.Text;
            if (Directory.Exists(strSourceDir) == false)
            {
                lblMsg.Text = "指定转化程序文件目录不存在!";
                return;
            }
            if (Directory.Exists(strSaveDir) == false)
            {
                Directory.CreateDirectory(strSaveDir);
            }
            WritePrivateProfileString("SourceDir", "FilePath", strSourceDir, strIniPath);
            WritePrivateProfileString("SaveDir", "FilePath", strSaveDir, strIniPath);
            RunConverFile();
        }
        private void RunConverFile()
        {
            string fileDir = txtSourcePath.Text;           
            string fileName;
            string filePath;
            int chlstFileCount = chlstFile.Items.Count;
            for (int i = 0; i < chlstFileCount; i++)
            {
                if (chlstFile.GetItemChecked(i) == true)
                {
                    fileName = chlstFile.GetItemText(chlstFile.Items[i]);
                    filePath = fileDir + "\\" + fileName;
                    RunConvert(filePath,fileName);
                }
            }
            lblMsg.Text = "程序转化完成!";

        }
        private void RunConvert(string filePath,string fileName)
        {
            string strSaveDir = txtSavePath.Text;   
            
            string savePath = strSaveDir + "\\" + fileName;
            if (File.Exists(savePath) == true)
            {
                File.Delete(savePath);
            }
            if (File.Exists(filePath) == false)
            {
                lblMsg.Text =filePath+ "文件不存在,请刷新确定是否有此文件!";
                return;
            }
            string strLine;         
            bool isPrint = false;
            double dG00X=0;
            double dG00XFirst=0;
    
            int indexX;
            int indexY;
            int i=0;
            ArrayList aryTemp = new ArrayList();
            string strTemp;
            string strTemp1="";
            int iLine=0;
            int iTextNum = 0;
            int indexFormat = -1;
            using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.UTF8))
            {
              
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((strLine = sr.ReadLine()) != null)
                {
                    if (strLine.IndexOf("T45") > -1)
                    {
                        WriteTxt(savePath, strLine);
                        isPrint = true;
                    }
                  
                    if (strLine.IndexOf("T21") > -1)
                    {                    
                        isPrint = false;
                    }
                    if (strLine.IndexOf("T0") > -1)
                    {
                        isPrint = false;
                    }
                    if (strLine.IndexOf("M09") > -1)
                    {
                        
                        isPrint = false;
                    }
                    if (isPrint == true)
                    {                       
                        if (strLine.IndexOf("M65") > -1)
                        {
                            WriteTxt(savePath, strLine);                          
                        }
                        if (strLine.IndexOf("G00") > -1)
                        {
                            i++;
                            indexX = strLine.IndexOf("X");
                            indexY = strLine.IndexOf("Y");
                            dG00X = double.Parse(strLine.Substring(indexX + 1, indexY - indexX - 1).Trim());
                            
                        }
                        if (i == 1)
                        {
                            if (strLine.IndexOf("G00") > -1)
                            {
                                dG00XFirst = dG00X;
                                aryTemp.Add(strLine);
                            }
                            if (strLine.IndexOf("#MSG") > -1)
                            {
                                aryTemp.Add(strLine);
                            }
                            if (strLine.IndexOf("M64") > -1)
                            {
                                aryTemp.Add(strLine);
                            }
                           
                        }
                        if (i > 1)
                        {
                            if (dG00X == dG00XFirst)
                            {
                                if (strLine.IndexOf("Text1:") > -1)
                                {
                                    aryTemp.Add(strLine);
                                }
                            }
                            else
                            {
                                //WriteTxt(savePath, strLine);  
                                if (strLine.IndexOf("M11") > -1 || strLine.IndexOf("M12") > -1 || strLine.IndexOf("G04") > -1)
                                {

                                }
                                else
                                {                                  
                                    aryTemp.Add(strLine);
                                    if (strLine.IndexOf("G00") > -1)
                                    {
                                        i = 1;
                                        dG00XFirst = dG00X;                                        
                                    }
                                }                  
                                
                            }
                        }

                    }
                    else
                    {
                        int iTempCount = aryTemp.Count;
                        if (iTempCount > 0)
                        {
                            
                            for (int k = 0; k < iTempCount; k++)
                            {
                                strTemp = aryTemp[k].ToString();
                                int k1 = k;
                                indexFormat = -1;
                                if (strTemp.IndexOf("Format:") > -1)
                                {
                                        iLine = 0;
                                        while (indexFormat == -1)
                                        {
                                            k1++;                                       
                                            strTemp1 = aryTemp[k1].ToString();                                    
                                            indexFormat = strTemp1.IndexOf("Format:");
                                            if (strTemp1.IndexOf("Text1:") > -1)
                                            {
                                                iLine++;
                                            }
                                            if (k1 == iTempCount - 1)
                                            {
                                                //iLine = 1;
                                                indexFormat = 0;
                                            }
                                           
                                        }
                                        //if (indexFormat >2)
                                        //{
                                        //    iLine = k1 - k-2;
                                        //    indexFormat = -1;
                                        //}
                                   
                                    
                                }                               
                             
                                if (strTemp.IndexOf("Format:") > -1)
                                {
                                    string strLineNum = "L=" + iLine.ToString();
                                    strTemp = strTemp.Replace("L=1", strLineNum);
                                }
                                if (strTemp.IndexOf("Text1:") > -1)
                                {
                                    if (iLine > 1)
                                    {
                                        iTextNum++;
                                    }
                                    else
                                    {
                                        iTextNum = 1;
                                    }
                                    string strTextNum;
                                    strTextNum = "Text" + iTextNum.ToString();
                                    strTemp = strTemp.Replace("Text1", strTextNum);
                                    if (iTextNum == iLine)
                                    {
                                        strTemp=strTemp + "\r\nM11\r\nG04 X0.1\r\nM12";
                                        iTextNum = 0;
                                    }
                                   
                                }
                                WriteTxt(savePath, strTemp);                               
                            }//end for
                          
                            aryTemp.Clear();                            
                        }                      
                        WriteTxt(savePath, strLine);
                    }//end print

                   
                }//end while

            }//end using            
        }
        
        private  void WriteTxt(string txtPath, string strMsg)
        {
          
            using (FileStream fs = new FileStream(txtPath, FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))
                {
                    sw.WriteLine(strMsg);
                }
            }
        }
        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            int chlstFileCount = chlstFile.Items.Count;
            if (chkSelectAll.Checked == true)
            {
                for (int i = 0; i < chlstFileCount; i++)
                {
                    chlstFile.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int j = 0; j < chlstFileCount; j++)
                {
                    chlstFile.SetItemChecked(j, false);
                }
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            string sourceFileDir;
            string saveFileDir;
            if (File.Exists(strIniPath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString("SourceDir", "FilePath", "", temp, 1024, strIniPath);
                sourceFileDir = temp.ToString();
                txtSourcePath.Text = sourceFileDir;
                GetPrivateProfileString("SaveDir", "FilePath", "", temp, 1024, strIniPath);
                saveFileDir = temp.ToString();
                txtSavePath.Text = saveFileDir;
            }
            ImportSourceFile(txtSourcePath.Text);
            lblMsg.Text = "";
        }

        private void btnFreshen_Click(object sender, EventArgs e)
        {
            chkSelectAll.Checked = false;
            chlstFile.Items.Clear();
            if (txtSourcePath.Text.Length > 2)
            {
                ImportSourceFile(txtSourcePath.Text);
            }
        }
    }
}
[SourceDir]
FilePath=E:\Test\333
[SaveDir]
FilePath=E:\Test\3331
原文地址:https://www.cnblogs.com/ike_li/p/1529375.html