内部循环IO操作

时间:2012-06-03 23:08:01

标签: c# io console-application

我正在编写一个小型控制台应用程序,它必须用另一个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;
}

3 个答案:

答案 0 :(得分:3)

如果您点击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++;
}

答案 1 :(得分: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以外的任何内容), 它将复制文件并打印“\ nok \ n”和“1”。然后它会再次询问您,如果按x,它将会停止。

答案 2 :(得分:1)

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

原因是Console.Read只在你点击'enter'时返回,所以它读取3个字符; 's''\ r','\ n'(最后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;
}