Delphi的TStringList实在太好用啦,不但可以读取/写入文本文件,而且还可以像Value["KeyName"]这样使用,刚学C#没多久,教程上没有类似的类,自己学习写一下吧。代码如下:
using System;
using System.Text;
namespace OverBlueUtil.StringUtils
{
///
/// 字符串列表对象,可以保存多行的字符串,可以保存字符串列表到文件中,也可以从文本文件中读取
/// 数据到字符串列表中。
///
class StringList
{
private System.Collections.ArrayList Lines = new System.Collections.ArrayList();
///
/// 创建一个字符串列表对象
///
public StringList()
{
}
///
/// 直接返回字符串列表的第 Index 行字符串
///
///
/// 返回指定行的数据
public string this[int Index]
{
get
{
if (Lines.Count <= Index)
{
throw new InvalidOperationException("Index值超界啦 !");
}
else
{
return Lines[Index].ToString();
}
}
set
{
if (Lines.Count <= Index)
{
throw new InvalidOperationException("Index值超界啦 !");
}
else
{
Lines[Index] = value;
}
}
}
///
/// 返回此字符串列表总行数
///
///
public int Count()
{
return Lines.Count;
}
///
/// 增加一行字符串到字符串列表中
///
///
public int Add(string StrValue)
{
return Lines.Add(StrValue);
}
///
/// 清除字符串列表中的所有内容
///
public void Clear()
{
Lines.Clear();
}
///
/// 读取字符串列表中 KeyName = ??? 的值
///
///
/// 指定KeyName的值,如果字符串列表中不包含指定的KeyName,则返回空字符串
public string GetValue(string KeyName)
{
if (Lines.Count == 0) return "";
for (int i = 0; i < Lines.Count; i++)
{
string tmpKeyName = Lines[i].ToString().Substring(0, KeyName.Length + 1).ToLower();
if (KeyName.ToLower() + "=" == tmpKeyName)
{
string tmpValue = Lines[i].ToString();
tmpValue = tmpValue.Substring(KeyName.Length + 1, tmpValue.Length - KeyName.Length - 1);
return tmpValue;
}
}
return "";
}
///
/// 读入字符串列表中 KeyName = ??? 的值,如果指定的KeyName不存在,则自动创建
///
///
public void SetValue(string KeyName, string KeyValue)
{
int Index = -1;
//查找 KeyName 在第几行
if (Lines.Count != 0)
{
for (int i = 0; i < Lines.Count; i++)
{
string tmpKeyName = Lines[i].ToString().Substring(0, KeyName.Length + 1).ToLower();
if (KeyName.ToLower() + "=" == tmpKeyName)
{
Index = i;
break;
}
}
}
if (Index == -1)
{
//如果没有键则添加一个
Lines.Add(KeyName + "=" + KeyValue);
}
else
{
//修改此键的值
Lines[Index] = KeyName + "=" + KeyValue;
}
}
///
/// 保存字符串列表到指定的文本文件中
///
///
public void SaveToFile(string FileName)
{
System.IO.File.WriteAllLines(FileName, (string[])Lines.ToArray(typeof(string)));
}
///
/// 从指定的文本中读取文本内容到字符串列表中
///
///
/// 成功则返回 True,否则返回 False
public bool LoadFromFile(string FileName)
{
if (System.IO.File.Exists(FileName) == true)
{
Lines.Clear();
Lines.AddRange(System.IO.File.ReadAllLines(FileName));
return true;
}
else
{
throw new InvalidOperationException(FileName+" 文件不存在 !");
return false;
}
}
}
}测试一下:
1)简单写一个字符
StringList sl = new StringList();
sl.Add("这是一个测试");
sl.SaveToFile("C:\\ABC.TXT");2)写入并读取Value值
StringList sl = new StringList();
sl.SetValue("ConnStr", "C:\ABCDEFG.DBF");
sl.SaveToFile("C:\\ABC.TXT"); //看看C:\ABC.TXT的内容是不是ConnStr=C:\ABCDEFG.DBF??sl.SetValue("ConnStr", "C:\HIJKLMN.DBF");
sl.SaveToFile("C:\\ABC.TXT"); //看看C:\ABC.TXT的内容是不是ConnStr=C:\HIJKLMN.DBF??
sl.Clear();
sl.LoadFromFile("C:\\ABC.TXT");
MessageBox.Show(sl.GetValue("ConnStr")); //应该显示C:\HIJKLMN.DBF
MessageBox.Show(sl.GetValue("CCCCC")); //应该显示"",因为根本没有此KeyName