c# - 在输入文件中找不到字符串

标签 c# streamreader

我有一个文本文件,我想在其中插入一行代码。使用我的链接列表,我相信我可以避免必须取出所有数据,对其进行排序,然后将其放入一个新的文本文件中。 我所做的是想出下面的代码。我设置了 bool 值,但它仍然不起作用。我检查了调试器,它似乎正在检查整个列表(大约 10,000 行)并且没有发现任何正确的东西,所以它没有插入我的代码。

为什么或这段代码有什么问题?

List<string> lines = new List<string>(File.ReadAllLines("Students.txt"));


 using (StreamReader inFile = new StreamReader("Students.txt", true))
 {
    string newLastName = "'Constant";
    string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 'mdcant@mail.usi.edu 4.000000 )";
    string line;
    string lastName;
    bool insertionPointFound = false;
    for (int i = 0; i < lines.Count && !insertionPointFound; i++)
    {
        line = lines[i];
        if (line.StartsWith("(LIST (LIST "))
        {
            values = line.Split(" ".ToCharArray());
            lastName = values[2];
            if (newLastName.CompareTo(lastName) < 0)
            {
                lines.Insert(i, newRecord);
                insertionPointFound = true;
            }
        }
    }
    if (!insertionPointFound)
    {
        lines.Add(newRecord);
    }

最佳答案

您只是将文件读入内存,而不是将其提交到任何地方。

恐怕您将不得不加载并完全重写整个文件。文件支持追加,但不支持插入。

你可以像读取文件一样写入文件

string[] lines;
/// instanciate and build `lines`
File.WriteAllLines("path", lines);

WriteAllLines 也接受一个 IEnumerable,因此您可以根据需要将字符串的 List 传递到那里。


还有一个问题:您似乎正在阅读您的文件两次。一个使用 ReadAllLines,另一个使用 StreamReader

关于c# - 在输入文件中找不到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505117/

相关文章:

c# - 何时注册将调用 Form.Invoke 的方法?

c# - EF 和自动映射器。更新嵌套集合

c# - 系统.IO.IOException : The process cannot access the file because it is being used by another process

html - StreamReader 返回符号(使用 HttpWebRequest)

c# - StreamReader 和读取 XML 文件

c# - Unity 中的回合制网络

c# - 转换方法以使用任何枚举

c# - ScriptManager.GetCurrent ( Page ).IsInAsyncPostBack 在运行时抛出错误

c# - 从文本文件中获取数据并将其输入二维数组

c# - 跳过 HttpResponseMessage Content.ReadAsStream 的第一行(CSV 标题行)