c#读取及写入配置文件相对来说比较简单,这里以WPF为例,读取ini配置文件,首先大家先添加一个名为“ConfigLoad.cs”的类文件,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace wpf读取ini配置文件
{
class ConfigLoad
{
public ConfigLoad(string conFilePath)
{
this.conFilePath = conFilePath;
ReadConfig();
}
/// <summary>
/// 配置文件的目录
/// </summary>
#region ConFilePath
string conFilePath;
public string ConFilePath
{
set { conFilePath = value; }
get { return conFilePath; }
}
#endregion
/// <summary>
/// 配置文件属性值
/// </summary>
private List<string> configName = new List<string>();//名称集合
private List<string> configValue = new List<string>(); //数值集合
/// <summary>
/// 读取配置文件的属性值
/// </summary>
public bool ReadConfig()
{
//检查配置文件是否存在
if (!File.Exists(this.conFilePath))
{
return false;
}
StreamReader sr = new StreamReader(this.conFilePath, Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
line = line.Trim();
string cName, cValue;
string[] cLine = line.Split('=');
if (cLine.Length == 2)
{
cName = cLine[0].ToLower();
cValue = cLine[1].ToLower();
configName.Add(cName);
configValue.Add(cValue);
}
}
sr.Close();
return true;
}
#region GetConfigValue
/// <summary>
/// 返回变量的字符串值
/// </summary>
/// <param name="cName">变量名称</param>
/// <returns>变量值</returns>
public string GetStringValue(string cName)
{
for (int i = 0; i < configName.Count; i++)
{
if (configName[i].Equals(cName.ToLower()))
{
return configValue[i];
}
}
return null;
}
public int GetIntValue(string cName)
{
for (int i = 0; i < configName.Count; i++)
{
if (configName[i].Equals(cName.ToLower()))
{
int result;
if (int.TryParse(configValue[i], out result))
{
return result;
}
}
}
return 0;
}
public float GetFloatValue(string cName)
{
for (int i = 0; i < configName.Count; i++)
{
if (configName[i].Equals(cName.ToLower()))
{
float result;
if (float.TryParse(configValue[i], out result))
{
return result;
}
}
}
return 0;
}
#endregion
}
public class ConfigSet
{
public ConfigSet(string configFilePath, bool isRead)
{
this.configFilePath = configFilePath;
if (File.Exists(this.configFilePath) && isRead)
{
ReadConfig();
}
}
public ConfigSet(string configFilePath)
{
this.configFilePath = configFilePath;
}
private string configFilePath;
private List<string> configName = new List<string>();//名称集合
private List<string> configValue = new List<string>(); //数值集合
/// <summary>
/// 设置写入配置文件的值
/// </summary>
/// <param name="cName">属性名称</param>
/// <param name="cValue">值</param>
public void SetConfigValue(string cName, string cValue)
{
bool ishere = false;
//检查是否已经存在.
if (configName.Count != 0)
{
for (int i = 0; i < configName.Count; i++)
{
if (configName[i].Equals(cName.ToLower()))
{
configValue[i] = cValue;
ishere = true;
}
}
}
if (!ishere)
{
configName.Add(cName);
configValue.Add(cValue);
}
}
/// <summary>
/// 将设置的值写入到ini文件中.
/// </summary>
/// <param name="cf">是否追加到文件</param>
/// <returns></returns>
public bool WriteConfigToFile(ConfigFile cf)
{
StreamWriter sw;
switch (cf)
{
case ConfigFile.newFile:
{
sw = new StreamWriter(this.configFilePath, false);
break;
};
case ConfigFile.appendFile:
{
sw = new StreamWriter(this.configFilePath, true);
break;
}
default:
{
sw = new StreamWriter(this.configFilePath);
break;
}
}
try
{
for (int i = 0; i < configName.Count; i++)
{
sw.WriteLine("{0}={1}", configName[i].ToLower(), configValue[i]);
}
}
catch
{
return false;
}
finally
{
sw.Close();
}
return true;
}
/// <summary>
/// 读取配置文件的属性值
/// </summary>
private bool ReadConfig()
{
StreamReader sr = new StreamReader(this.configFilePath, Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
line = line.Trim();
string cName, cValue;
string[] cLine = line.Split('=');
if (cLine.Length == 2)
{
cName = cLine[0].ToLower();
cValue = cLine[1].ToLower();
configName.Add(cName);
configValue.Add(cValue);
}
}
sr.Close();
return true;
}
}
/// <summary>
/// 写入文件属性
/// </summary>
public enum ConfigFile { newFile, appendFile }
}
首先,我们在Debug目录下添加一个名为“config.ini”的配置文件,里面写入如下内容,如图:
然后我们再MainWindow里面添加三个Label控件、三个TextBox控件和一个Button控件,代码如下:
<Window x:Class="wpf读取ini配置文件.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="106,78,0,0" Name="textBox1" VerticalAlignment="Top" Width="255" />
<Label Content="URL1:" Height="28" HorizontalAlignment="Left" Margin="38,76,0,0" Name="label1" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="106,130,0,0" Name="textBox2" VerticalAlignment="Top" Width="255" />
<Label Content="URL1:" Height="28" HorizontalAlignment="Left" Margin="38,128,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="106,177,0,0" Name="textBox3" VerticalAlignment="Top" Width="255" />
<Label Content="URL1:" Height="28" HorizontalAlignment="Left" Margin="38,175,0,0" Name="label3" VerticalAlignment="Top" />
<Button Content="修改" Height="23" HorizontalAlignment="Left" Margin="112,242,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
最后我们在后台编写读取和写入ini配置文件的代码,代码如下:
/// <summary>
///读取配置文件
/// </summary>
///
private void ReadURL()
{
//设置配置文件
ConfigLoad con = new ConfigLoad("config.ini");
//textbox读取配置文件默认值
textBox1.Text = con.GetStringValue("url1");
textBox2.Text = con.GetStringValue("url2");
textBox3.Text = con.GetStringValue("url3");
}
/// <summary>
///写入配置文件
/// </summary>
///
private void Write()
{
try
{
ConfigSet cs = new ConfigSet("config.ini", true);
cs.SetConfigValue("url1", textBox1.Text.ToString());
cs.SetConfigValue("url2", textBox2.Text.ToString());
cs.SetConfigValue("url3", textBox3.Text.ToString());
cs.WriteConfigToFile(ConfigFile.newFile);
MessageBox.Show("修改配置文件URL成功");
}
catch(Exception e)
{
MessageBox.Show("修改配置文件URL失败");
}
finally
{
}
}
我们想要使用读取及写入配置文件的话只需在指定位置添加即可,比如,我是在初始化的时候添加读取配置文件代码并显示在textbox中,在button修改事件中添加修改配置文件代码。效果如图: