【问题标题】:Delete specific line in a text file , using Sytem.IO使用 Sytem.IO 删除文本文件中的特定行
【发布时间】:2015-10-01 05:39:46
【问题描述】:

我有一个问题,删除文本列表,而不删除保存在文件中的所有文本,如果我搜索 1,则 1 中的行将被删除,而另一行不会受到影响是示例输出..

样本输出:

耐克 SB 8000 1

勒布朗 7 9000 2

这是我的代码:

private void btnDelete_Click(object sender, EventArgs e)
    {

        try
        {
            string[] InventoryData = File.ReadAllLines("Inventory.txt");
            for (int i = 0; i < InventoryData.Length; i++)
            {
                if (InventoryData[i] == txtSearch.Text)
                {
                        System.IO.File.Delete("Inventory.txt");            
                }

            }

        }
        catch
        {
            MessageBox.Show("File or path not found or invalid.");
        }
    }

【问题讨论】:

  • 当您System.IO.File.Delete("Inventory.txt"); 时,您会期待什么。除了那一行,你必须重新写一遍
  • @AlgorithNewbie:您是否打算这样做:如果一行包含我正在搜索的单词,则删除该行?因为,在这里,如果文件包含您要搜索的单词,您将删除整个文件。
  • 附带说明,您可能希望使用 FileHelpers 库来轻松操作表格数据,而不是自己破解文件,或者您可能选择使用随机(二进制)访问文件来修改文件在旅途中。

标签: c# system.io.file


【解决方案1】:

无法在磁盘中编辑文本文件的内容。您必须再次覆盖该文件。

您还可以将数组转换为列表并使用List(T).Remove 方法从中删除第一个匹配项。

string[] inventoryData = File.ReadAllLines("Inventory.txt");
List<string> inventoryDataList = inventoryData.ToList();

if (inventoryDataList.Remove(txtSearch.Text)) // rewrite file if one item was found and deleted.
{
    System.IO.File.WriteAllLines("Inventory.txt", inventoryDataList.ToArray());
}

如果您想在一次搜索中删除所有项目,请使用List&lt;T&gt;.RemoveAll 方法。

if(inventoryDataList.RemoveAll(str => str == txtSearch.Text) > 0) // this will remove all matches.

编辑:对于较旧的 .Net Framework 版本(3.5 及更低版本),您必须调用 ToArray(),因为 WriteAllLines 仅将数组作为第二个参数。

【讨论】:

  • WriteAllLines 会覆盖内容,因此不需要Delete
  • 运行时会报错,描述为 1. System.IO.File.WriteAllLines(string, string[]); 的最佳重载方法匹配;有一些无效的论点。 2. 参数'2':不能从'System.Collection.Generic.list'转换为'string[]'
  • 试试System.IO.File.WriteAllLines("Inventory.txt", inventoryDataList.ToArray());@AlgorithNewbie
  • @AlgorithNewbie 查看编辑。还是报错?
【解决方案2】:

你可以用 linq 做到这一点。

lines = File.ReadAllLines("Inventory.txt").Where(x => !x.Equals(txtSearch.Text));
File.WriteAllLines("Inventory.txt", lines);

【讨论】:

    【解决方案3】:

    您完全做错了,而是从集合中删除该行并写下该行

    List<string> InventoryData = File.ReadAllLines("Inventory.txt").ToList();            
    
    for (int i = 0; i < InventoryData.Count; i++)
    {
        if (InventoryData[i] == txtSearch.Text)
        {
            InventoryData.RemoveAt(i);
            break;            
        }
    }
    
    System.IO.File.WriteAllLines("Inventory.txt", InventoryData.AsEnumerable());
    

    【讨论】:

    • 运行时会报错,描述为 1. System.IO.File.WriteAllLines(string, string[]); 的最佳重载方法匹配;有一些无效的论点。 2. 参数'2':不能从'System.Collection.Generic.list'转换为'string[]'
    • @AlgorithNewbie,不,不应该。您使用的是哪个框架版本?
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2011-01-07
    • 2011-08-13
    相关资源
    最近更新 更多