删除文本文件中某些文本的行 [英] Removing line with certain text in text file

查看:71
本文介绍了删除文本文件中某些文本的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含以下数据:



商品名称

价格

数量

商品名称

价格

数量

商品名称

价格
数量

...



然后我将这些数据发送到listview,代码如下:



I have a text file which looks contain such data:

Item name
Price
Quantity
Item name
Price
Quantity
Item name
Price
Quantity
...

Then I''m getting this data to listview with such code:

listView1.Columns.Add("Item name / title", 400);
listView1.Columns.Add("Selling price", 70);
listView1.Columns.Add("Quantity / In stock", 100);


using (StreamReader sr = new StreamReader(@"test.txt"))
{
    while (-1 < sr.Peek())
    {
        try
        {
            string name = sr.ReadLine();
            string email = sr.ReadLine();
            string quantity = sr.ReadLine();
            var lvi = new ListViewItem(name);
            lvi.SubItems.Add(email);
            lvi.SubItems.Add(quantity);
            listView1.Items.Add(lvi);
        }
        catch (Exception) { }
    }
    sr.Close();
}





现在我正在实施删除项目功能,我想这样做:

- 添加按钮,在其上单击所选项目从文本文件中删除(通过查找包含项目名称的行,将其删除并删除后面的两行)。然后通过删除单个项目或清除并重新加载列表来刷新列表。



我现在的奋斗是 - 如何查找和删除文本文件中的行?



Now I''m implementing removing item function, I want to do it like this:
- Add button, on which click selected item is deleted from text file (by finding a line which contains item name, removing it and removing next two lines after it too). And then refresh list either by removing single items or clearing and reloading list.

My struggle now is - how to find and remove the lines in text file?

推荐答案

这就是为什么这种东西的文本文件不常见的原因之一:它是PITA。



文本文件不支持任何形式的记录,因此您不能说删除此行,因为文本文件并不真正了解行 - 它知道换行符,不一样总的来说。



为了从文本文件中删除一行,你必须:

1)阅读文本文件到你要删除的行的点,同时将数据写入新文件。

2)读取你要删除的行,不将其写入输出文件

3)读取文件的其余部分,将其写入输出文件。

4)关闭两个文件。

5)删除orig inal file。

6)将输出文件重命名为原始文件名。



插入行的过程大致相同。



如果您想定期执行此操作,或者甚至让多个用户查看该文件,那么我强烈建议您转移到更结构化的存储解决方案,例如小型数据库。
This is one of the reasons why usign text files for this kind of thing is not common: it''s a PITA.

Text files do not support records of any form, so you can''t say "delete this line" because a text file does not really know about lines - it knows about newline characters, byt that is not the same thing at all.

In order to delete a line from a text file, you must:
1) Read the text file up to the point of the line you wish to delete, writing the data out to a new file at the same time.
2) Read past the line you want rid off, no writing it to the output file
3) Read the rest of the file, writing it to the output file.
4) Close both files.
5) Delete the original file.
6) Rename the output file to the original file name.

The process is much the same for inserting lines.

If you want to do this on a regular basis, or even have more than one user looking at the file, then I would strongly suggest you move to a more structured storage solution, such as a small database.


这篇关于删除文本文件中某些文本的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆