【问题标题】:Reading and deleting a Random Line from a .txt File in C#从 C# 中的 .txt 文件中读取和删除随机行
【发布时间】:2020-12-01 16:07:22
【问题描述】:

我想在 C# 控制台中创建一个随机数生成器,但它没有第二次显示数字。所以我做了一个脚本,它从 .txt 文件中选择一个随机数,读取它,然后从 .txt 中删除它。

我知道没有阅读该行并给出输出的部分,因为我首先想获得删除部分。问题是,它只是删除了完整的 .txt 文件。

脚本:

using System;
using System.IO;

namespace Random_Number_generator
{
    class Program
    {
        static void Main(string[] args)
        {
            //Generates the random Number
            int RandomNumber;
            string BGInfo;
            Random rnd = new Random();
            int GetRandomInt(int min, int max)
            {
                return rnd.Next(min, max);
            }
            RandomNumber = GetRandomInt(1, 25);

            // 1. Read the content of the file
            string[] readText = File.ReadAllLines("D:/BG_Numbers.txt");
            Console.WriteLine("Readed: " + readText);
            Console.ReadKey();

            // 2. Empty the file
            File.WriteAllText("D:/BG_Numbers.txt", String.Empty);

            using (StreamWriter writer = new StreamWriter("D:/BG_Numbers.txt"))
            {
                foreach (string s in readText)
                {
                    if (!s.Equals(RandomNumber))
                    {
                        writer.WriteLine(s);
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 如果您能提供更多关于究竟是什么不工作的信息将会很有帮助。
  • 提示:您可以使用 == 测试是否相等,或者使用 != 测试是否不相等。然后s! =RandomNumber 会出错,因为您将字符串与 int 进行比较
  • 你的意思是每次运行时都会产生一个随机数而不重复先前的数字?措辞不清楚。

标签: c# random


【解决方案1】:

当您将从文件中读取的数字与随机生成的数字进行比较时,您实际上是将stringint 进行比较,因此您的条件永远不会是true。您可以使用其ToString 值将随机数更改为string,也可以在读取文件内容时将文件中的行转换为实际数字,如下例所示:

const string fileName = "D:/BG_Numbers.txt";

// Generate random number
int randomNumber;
Random random = new Random();
randomNumber = random.Next(1, 25);
Console.WriteLine($"Your random number is: {randomNumber}");
Console.ReadKey();

// Read the file content
int[] numbers = File.ReadAllLines(fileName).Select(int.Parse).ToArray();
Console.WriteLine($"Read: [{string.Join(", ", numbers)}]");
Console.ReadKey();

// Clear the file content
File.WriteAllText(fileName, string.Empty);
Console.WriteLine("File content cleared.");
Console.ReadKey();

using (StreamWriter writer = new StreamWriter(fileName))
{
    foreach (int number in numbers)
    {
        if (!number.Equals(randomNumber)) // This line was comparing 'string' with 'int'
        {
            writer.WriteLine(number);
        }
    }
}

Console.WriteLine("Done!");

【讨论】:

  • 感谢您的回答。现在它工作了一半,因为它再次将数字写入文件,但没有删除任何数字。我尝试了几件事,但没有帮助。我很新(就像 c# 中的 3 天)。你知道问题可能是什么吗?再次感谢您的回答。是因为“foreach (int number ...”在 if (!number.Equals..." 之前吗?
  • @beginner 它确实删除了一个随机的数字,我认为这就是你想要的。
  • 生成了一个随机数,不能保证它会出现在文件中(并且可以删除)。那么可能生成的数字在之前的运行中已经被删除了?
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2022-06-12
  • 2020-10-09
  • 1970-01-01
相关资源
最近更新 更多