现在的位置: 首页 > 综合 > 正文

c# 中读写ini文件(C#操作文本文件、C#读写文本文件)

2013年06月19日 ⁄ 综合 ⁄ 共 1806字 ⁄ 字号 评论关闭

在程序所在位置建立测试文件test.ini,其内容为:
USERNAME  = 小李
USERAGE   = 28
USERSEX   = 男
USERADDR  = 地球村

 

//默认新建windows 窗口工程,在Form1.cs中添加如下命名空间
using System.IO;

 

//在窗口上添加两个按钮,分别取名"读取"、"写入"。

 

//在public partial class Form1 : Form 类中添加如下的私有变量
private string sAppPaht = Application.StartupPath; //获取应用程序路径

private string sName = "", sAge = "", sSex = "", sAdd = "";

 

//在"读取"按钮的点击消息响应中添加如下代码

{
  FileInfo fiExit = new FileInfo(sAppPaht + "//test.ini");

  //使用StreamReader进行文本读取操作
  if(fiExit.Exists)
  {
    StreamReader SetContent = YnExist.OpenText();
    string strLine = SetContent.ReadLine();
    int ZeroIndex = 0;

    while (strLine != null)
    {
             if (((strLine.Trim()).ToUpper()).StartsWith("USERNAME"))
             {
                 ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                 if (ZeroIndex > -1)
                 sName = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1);
             }

             if (((strLine.Trim()).ToUpper()).StartsWith("USERAGE"))
             {
                 ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                 if (ZeroIndex > -1)
                 sAge = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1);
             }
             .................................
             strLine = SetContent.ReadLine();
     }

    SetContent.Close();

    strLine = "姓名:"+sName + "年龄:"+sAge + "性别"+sSex + "住址:"+sAdd;

    MessageBox.Show(strLine);

  }
}
//在"写入"按钮的点击消息响应中添加如下代码
//使用StreamWriter进行文本文件写入操作

 

{

string sTextPath = sAppPaht + "//test.ini";
StreamWriter sw = new StreamWriter(@sTextPath, true); //false为直接覆盖该文件,true就直接添加在文件末尾

sName = "老张";
sAge  = "30";
sSex  = "男";
sAdd  = "月球村";

sw.Write("USERNAME   =" + sName);
sw.WriteLine();

sw.Write("USERAGE    =" + sAge);
sw.WriteLine();

sw.Write("USERSEX    =" + sSex);
sw.WriteLine();

sw.Write("USERADDR   =" + sAdd);
sw.WriteLine();

sw.Close();

}

 

 

写完后,打开test.ini文件,其内容为:
USERNAME  = 小李
USERAGE   = 28
USERSEX   = 男
USERADDR  = 地球村

USERNAME  = 老张
USERAGE   = 30
USERSEX   = 男
USERADDR  = 月球村

抱歉!评论已关闭.