C#中读写INI文件

在网上找了关于ini文件读写方法,还是没有找到ini文件中有一个Section多个Key的读写情况,在一篇C++文章中得到点提示操作如下:
1.创建ini文件读写类:
using  System.Runtime.InteropServices;
using  System.Text;

namespace  INIDemo
{
    
/**////  <summary>
    
///  读写ini文件的类
    
///  调用kernel32.dll中的两个API:WritePrivateProfileString,GetPrivateProfileString
    
///  来实现对ini  文件的读写。
    
///  INI文件是文本文件,
    
///  由若干节(section)组成,
    
///  在每个带括号的标题下面,
    
///  是若干个关键词(key)及其对应的值(value) 
    
///  例如:
    
///  [Section]
    
///  Key=value
    
///  </summary>

    public class IniFile
    
{
        
/**////  <summary>
        
///  ini文件名称(带路径)
        
///  </summary>

        public string filePath;

        
/**////  声明读写INI文件的API函数
        [DllImport("kernel32")]
        
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport(
"kernel32")]
        
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        
/**////  <summary>
        
///  类的构造函数
        
///  </summary>
        
///  <param  name="INIPath">INI文件名</param>  

        public IniFile(string INIPath)
        
{
            filePath 
= INIPath;
        }

        
/**////  <summary>
        
///  写INI文件
        
///  </summary>
        
///  <param  name="Section">Section</param>
        
///  <param  name="Key">Key</param>
        
///  <param  name="value">value</param>

        public void WriteInivalue(string Section, string Key, string value)
        
{
            WritePrivateProfileString(Section, Key, value, 
this.filePath);
        }

        
/**////  <summary>
        
///  读取INI文件指定部分
        
///  </summary>
        
///  <param  name="Section">Section</param>
        
///  <param  name="Key">Key</param>
        
///  <returns>String</returns>  

        public string ReadInivalue(string Section, string Key)
        
{
            StringBuilder temp 
= new StringBuilder(1024);
            
int i = GetPrivateProfileString(Section, Key, "读取错误", temp, 1024this.filePath);
            
return temp.ToString();
        }

    }

}


2. 测试INI文件读写
         // 写入ini文件
         private   void  button1_Click( object  sender, EventArgs e)
        
{
            
string filePath = Path.GetFullPath(@"demo.ini");
            IniFile iniFile 
= new IniFile(filePath);

            
//在一个section中写入一个key
            iniFile.WriteInivalue("Section1""Key1""Key1's Value");
            iniFile.WriteInivalue(
"Section2""Key2""Key2's Value");

            
//在一个section中写入多个key
            string[] fileNames = new string[] "file1""file2""file3""file4" };
            
string[] values = new string[] "value1""value2""value3""value4" };
            
for (int i = 0; i < 4; i++)
            
{
                iniFile.WriteInivalue(
"UseFileName", fileNames[i], values[i]);
            }

        }


        
// 读取ini文件
         private   void  button2_Click( object  sender, EventArgs e)
        
{
            
string filePath = Path.GetFullPath(@"demo.ini");
            IniFile iniFile 
= new IniFile(filePath);

            
//读取单个section的单个值
            string singleValue1 = null;
            
string singleValue2 = null;
            singleValue1 
= iniFile.ReadInivalue("Section1""Key1");
            singleValue2 
= iniFile.ReadInivalue("Section2""Key2");
            MessageBox.Show(singleValue1 
+ " " + singleValue2);

            
//读取单个section的多个值
            string[] fileNames = new string[] "file1""file2""file3""file4" };
            ArrayList values 
= new ArrayList();
            
for (int i = 0; i < 4; i++)
            
{
                values.Add(iniFile.ReadInivalue(
"UseFileName", fileNames[i]));
            }


            
int nCount = values.Count;
            
string multiValues = null;
            
for (int i = 0; i < nCount; i++)
            
{
                multiValues 
+= values[i].ToString() + " ";
            }

            MessageBox.Show(multiValues);
        }

结果:
[Section1]
Key1=Key1's Value
[Section2]
Key2=Key2's Value
[UseFileName]
file1=value1
file2=value2
file3=value3
file4=value4

转载于:https://www.cnblogs.com/zhusimu/archive/2008/07/12/1241439.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 可以使用 `System.IO` 命名空间下的 `StreamReader` 和 `StreamWriter` 类来 ini 文件,也可以使用 `System.Configuration` 命名空间下的 `ConfigurationManager` 类来ini 文件。 以下是使用 `StreamReader` 和 `StreamWriter` 类 ini 文件的示例代码: ```csharp using System.IO; // ini 文件 var lines = File.ReadAllLines("config.ini"); foreach (var line in lines) { if (line.StartsWith("#")) // 忽略注释 continue; var parts = line.Split('='); if (parts.Length != 2) // 忽略格式不正确的行 continue; var key = parts[0].Trim(); var value = parts[1].Trim(); // TODO: 处理 key 和 value } // ini 文件 using (var sw = new StreamWriter("config.ini")) { sw.WriteLine("# This is a config file."); sw.WriteLine("key1=value1"); sw.WriteLine("key2=value2"); // TODO: 入更多配置项 } ``` 如果你想使用 `ConfigurationManager` 类来ini 文件,需要先在项目的 `app.config` 或 `web.config` 文件添加配置节: ```xml <configuration> <configSections> <section name="myconfig" type="System.Configuration.NameValueSectionHandler" /> </configSections> <myconfig> <add key="key1" value="value1" /> <add key="key2" value="value2" /> <!-- 更多配置项 --> </myconfig> </configuration> ``` 然后在代码使用以下代码取配置项: ```csharp var config = ConfigurationManager.GetSection("myconfig") as NameValueCollection; if (config != null) { var value = config["key1"]; // 取 key1 对应的值 // TODO: 处理其他配置项 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值