日期:2014-05-18  浏览次数:20340 次

.net中读取文本文件或配置的数值怎么样做?
因为做个页面的需要,要用一个txt文件或ini文件保存一些用户设置的参数以便调用.但没做过.不知道怎么读出ini或txt文件里的数值.比如ini的内容为:
//myconfig
size=10;
color=red;
width=20....
怎么样读取里面的诸如size,color的值.请高手指点下.分不多了...

------解决方案--------------------
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

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

[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);


#endregion

读Ini文件#region 读Ini文件

public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
{
if(File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
return temp.ToString();
}
else
{
return String.Empty;
}
}

#endregion

写Ini文件#region 写Ini文件

public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
{
if(File.Exists(iniFilePath))
{
long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);
if(OpStation == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}

#endregion
}
}