这是我对这类问题的解决方案,当我想将一些数据保存在 .txt 配置文件中,然后我想检索该信息。
这是 WriteToFile 方法,它还会检查您插入的数据是否已经在文件中:
using System.IO;
public void WriteToFile(string newData, string _txtfile)
{
List<string> ListToWrite = new List<string>();
/// Reads every line from the file
try
{
using (StreamReader rd = new StreamReader(_txtfile, true))
{
while (true)
{
ListToWrite.Add(rd.ReadLine().Trim());
}
}
}
catch (Exception)
{
}
try
{
/// Check if the string that you want to insert is already on the file
var x = ListToWrite.Single(a => a.Contains(newData));
/// If there's no exception, means that it found your string in the file, so lets delete it.
ListToWrite.Remove(x);
}
catch (Exception)
{
/// If a exception is thrown, it did not find your string so add it.
ListToWrite.add(newData);
}
/// Now is time to write the NEW file.
if (ListToWrite.Count > 0)
{
using (StreamWriter tw = new StreamWriter(_txtfile, true))
{
try
{
foreach (string s in l)
{
tw.WriteLine(s);
}
}
catch (Exception)
{
break;
}
}
}
}
现在,如果您想通过使用字符串进行搜索来检索一些信息:
using System.IO;
public static string GetData(string _txtfile, string searchstring)
{
string res = "";
using (StreamReader rd = new StreamReader(_txtfile, true))
{
while (true)
{
try
{
string line = rd.ReadLine().Trim();
if (line.Contains(searchstring))
{
return line;
}
}
catch (Exception)
{
break;
}
}
}
return res;
}
您可以对此进行调整并使其变得更好,但这目前对我有用。