在写入txt文件时如何增加变量的值C#

罗克西阿切卡

我有以下程序:

数据库(如果可以在文本文件中称其为数据库)

写入文本文件时,我需要将记录ID增加一

我怎么能不理解/找到哪种方法可以实现增加ID的循环,有人可以告诉我吗?

我有一种方法可以格式化WPF文本框中的文本文件

using (StreamReader sr = new StreamReader("D:\\123.txt", true))
{
    while (sr.ReadLine() != null)
    {
        id++;
        using (StreamWriter txt = new StreamWriter("D:\\123.txt", true))
        {
            txt.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6}\n", id, TBName, TBLName, TBMName, TBInfo, TBMat, TBFiz));
        }
        MessageBox.Show("Данные успешно сохранены!");
    }
}

文本文件中的每个新条目如何将id增加1?

信息到数据网格的输出如下:

    private void Work()
    {
        try
        {
            List<Student> list = new List<Student>();
            using (StreamReader sr = new StreamReader(fileName, true))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var parsed = line.Split(' ');
                    list.Add(new Student
                        (
                           Convert.ToInt32(parsed[0]),
                           parsed[1],
                           parsed[2],
                           parsed[3],
                           Convert.ToInt32(parsed[4]),
                           Convert.ToInt32(parsed[5]),
                           Convert.ToInt32(parsed[6])
                        )); 
                }
            }
            DGridStudents.ItemsSource = list;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
史蒂夫

显示的代码有一些问题。首先,您无法使用StreamReader / StreamWriter类写入已打开以供读取的文件。但是即使可以,也请仔细查看其工作方式。首先,您打开文件,然后开始循环读取一行,然后在同一文件中写入新行,然后读取下一行(下一行可能与您刚写的相同)。
以更好的结果,您的文件将填满您的磁盘。

要增加最后一行中用作id的值,您可以使用此方法

// First read the whole file and get the last line from it
int id = 0;
string lastLine = File.ReadLines("D:\\123.txt").LastOrDefault();
if(!string.IsNullOrEmpty(line))
{
    // Now split and convert the value of the first splitted part
    var parts = line.Split();
    if(parts.Length > 0)
    {
        Int32.TryParse(parts[0], out id);
    }
}
 
// You can now increment and write the new line
id++
using (StreamWriter txt = new StreamWriter("D:\\123.txt", true))
{
     txt.WriteLine($"{id} {TBName} {TBLName} {TBMName} {TBInfo} {TBMat} {TBFiz}");
}

这种方法将迫使您阅读整个文件以找到最后一行。但是,您可以向txt中添加第二个文件(和索引文件),其名称相同,但扩展名为idx该文件将仅包含最后写入的数字

int id = 0;
string firstLine = File.ReadLines("D:\\123.idx").FirstOrDefault();
if(!string.IsNullOrEmpty(line))
{
    // Now split and convert the value of the first splitted part
    var parts = line.Split();
    if(parts.Length > 0)
    {
        Int32.TryParse(parts[0], out id);
    }
}
id++
using (StreamWriter txt = new StreamWriter("D:\\123.txt", true))
{
     txt.WriteLine($"{id} {TBName} {TBLName} {TBMName} {TBInfo} {TBMat} {TBFiz}");
}
File.WriteAllText("D:\\123.idx", id.ToString());

如果txt文件很大,则第二种方法可能会更好,因为它不需要读取整个txt文件,但是有更多可能失败的地方。您有两个文件要处理,这使IO错误的可能性增加了一倍,当然,我们甚至都没有考虑多用户方案。数据库,甚至是基于SQLite或Access这样的文件的数据库,都更适合于这些任务。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章