首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中读取和删除.txt文件中的随机行

,可以通过以下步骤实现:

  1. 读取.txt文件:使用StreamReader类打开文件,并使用ReadLine方法逐行读取文件内容。可以使用using语句确保文件在使用完后被正确关闭。
代码语言:txt
复制
using System;
using System.IO;

string filePath = "path/to/file.txt";
using (StreamReader sr = new StreamReader(filePath))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        // 处理每一行的内容
    }
}
  1. 获取随机行:可以使用Random类生成一个随机数,然后根据随机数选择要读取的行。可以使用List<string>来存储读取的所有行,然后根据随机数索引获取随机行。
代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.IO;

string filePath = "path/to/file.txt";
List<string> lines = new List<string>();

using (StreamReader sr = new StreamReader(filePath))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        lines.Add(line);
    }
}

Random random = new Random();
int randomIndex = random.Next(0, lines.Count);
string randomLine = lines[randomIndex];
  1. 删除随机行:可以使用StreamWriter类创建一个新的文件,并将除随机行以外的所有行写入新文件。然后可以使用File类的Delete方法删除原始文件,并使用File类的Move方法将新文件重命名为原始文件名。
代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.IO;

string filePath = "path/to/file.txt";
string tempFilePath = "path/to/temp.txt";
List<string> lines = new List<string>();

using (StreamReader sr = new StreamReader(filePath))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        lines.Add(line);
    }
}

Random random = new Random();
int randomIndex = random.Next(0, lines.Count);
lines.RemoveAt(randomIndex);

using (StreamWriter sw = new StreamWriter(tempFilePath))
{
    foreach (string line in lines)
    {
        sw.WriteLine(line);
    }
}

File.Delete(filePath);
File.Move(tempFilePath, filePath);

以上是在C#中读取和删除.txt文件中的随机行的完整步骤。请注意,这只是一个示例,实际应用中可能需要根据具体需求进行适当的修改和优化。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券