给定一个名为" config.cfg"的rawtext文件。具有以下内容:
entry1=value
entry2=value
entry3=value
以下函数仅读取SortedList中的第一个条目," entry1"。我不确定为什么会这样 - 它应该读取SortedList中的所有条目。
static public void setConfigValue(string key, object value)
{
var config = File.OpenText("./config.cfg");
SortedList<string, string> entries = new SortedList<string, string>();
while (config.BaseStream.Position < config.BaseStream.Length)
{
string temp = config.ReadLine();
if (temp != null)
{
string[] entry = temp.Split('=');
entries.Add(entry[0], entry[1]);
}
}
config.Close();
if (!entries.ContainsKey(key)) entries.Add(key, value.ToString());
else entries[key] = value.ToString();
List<string> listToSave = new List<string>();
for (int i = 0; i < entries.Count; i++) listToSave.Add(entries.Keys[i] + "=" + entries.Values[i]);
File.WriteAllLines("./config.cfg", listToSave);
}
有什么想法吗?
答案 0 :(得分:0)
使用BaseStream.Position不是检查End-Of-File的常规方法。
MSDN建议使用config.Peek() >= 0
作为您的while条件。您还可以查看EndOfStream
。我猜测位置检查并不是你认为的那样。
使用File.ReadLines
,甚至File.ReadAllText.Split('\n')
也可以。 (第二个可能会有回车问题,但至少你得到所有数据)。
MSDN读取所有行:MSDN
答案 1 :(得分:0)
您可以尝试这样的事情:
static public void setConfigValue(string key, object value)
{
var settings = File.ReadAllLines("config.cfg")
.Select((p) =>
{
string[] temp = p.Split('=');
return new { Key = temp[0], Value = temp[1] };
})
.ToDictionary((p) => p.Key, (p) => p.Value);
settings[key] = value.ToString();
var newContents = settings
.Select((p) => string.Concat(p.Key, '=', p.Value))
.OrderBy((p) => p, StringComparer.OrdinalIgnoreCase)
.ToList();
File.WriteAllLines("config.cfg", newContents);
}