循环内的 IO 操作

本文关键字:操作 IO 循环 | 更新日期: 2023-09-27 18:36:07

>我正在编写一个小的控制台应用程序,它必须用另一个txt文件覆盖一个txt文件,但是最终执行了3次,我认为这是因为IO写入过程比IO输出过程慢。任何人都可以帮助我如何只执行一次循环?

这是代码:

while (confirm != 'x') {
    Console.WriteLine(
        "Do you want to copy the archive to test2.txt? (y)es or e(x)it");
    confirm = (char)Console.Read();
    if (confirm == 's') {
        File.Copy("C:''FMUArquivos''test.txt", 
                  "C:''FMUArquivos''test2.txt", true);
        Console.WriteLine("'nok'n");
    }
    Console.WriteLine("'ncounter: " + counter);
    counter += 1;
}

循环内的 IO 操作

如果您点击 y<enter>,那么这将为您提供 3 个字符的序列"y" + <cr> + <lf> 并产生三次迭代,因此计数器将增加 3。请改用ReadLine

int counter = 0; 
while (true) {
    Console.WriteLine("Do you want to copy ...");
    string choice = Console.ReadLine();
    if (choice == "x") {
        break;
    }
    if (choice == "y") {
        // Copy the file
    } else {
        Console.WriteLine("Invalid choice!");
    }
    counter++;
}

现在我已经复制并运行了您的代码,我看到了您的问题。您应该将对"Read"的调用替换为"ReadLine",并将确认类型更改为字符串并进行比较。

原因是 Console.Read 仅在您点击"输入"时才返回,因此它读取 3 个字符;'s' '''r', ''' (最后 2 个是 Windows 上的换行符)。

有关 Console.Read 的 API 参考,请参阅此处:http://msdn.microsoft.com/en-us/library/system.console.read.aspx

试试这个;

string confirm = "";
int counter = 0;
while (confirm != "x")
{
    Console.WriteLine("Do you want to copy the archive to test2.txt? (y)es or e(x)it");
    confirm = Console.ReadLine();
    if (confirm == "s")
    {
        File.Copy("C:''FMUArquivos''test.txt",
            "C:''FMUArquivos''test2.txt", true);
        Console.WriteLine("'nok'n");
    }
    Console.WriteLine("'ncounter: " + counter);
    counter += 1;
}

试试这段代码:

var counter = 0;
Console.WriteLine("Do you want to copy the archive to test2.txt? (y)es or e(x)it");
var confirm = Console.ReadLine();
while (confirm != "x")
{
    File.Copy("C:''FMUArquivos''test.txt", "C:''FMUArquivos''test2.txt", true);
    Console.WriteLine("'nok'n");
    counter += 1;
    Console.WriteLine("'ncounter: " + counter);
    Console.WriteLine("Do you want to copy the archive to test2.txt? (y)es or e(x)it");
    confirm = Console.ReadLine();
}

它会询问您是否要继续,以及如果您按y(或除x以外的任何内容),它将复制文件并打印"'ok'"和"1"。然后它会再次询问你,如果你按 x ,它会停止。