2012-06-03 80 views
0

我正在寫一個小型控制檯應用程序,它必須用另一個txt文件覆蓋txt文件,但最終執行3次,我認爲這是因爲IO寫入過程比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; 
} 
+0

如果你只想執行一次代碼,爲什麼要使用循環呢?循環用於重複性代碼...? –

+1

@Kornel - 「問:我認爲這是因爲IO寫入過程比IO輸出過程慢。」答:胡說八道。我向你保證這不是問題;) – paulsm4

+1

我建議在另一個線程中執行IO操作:) –

回答

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++; 
} 
+0

Merci beaucoup Olivier! – Kornel

+0

Vocêébem-vindo。 –

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,它會停止。

+0

謝謝Yorye! – Kornel

1

現在我已經複製並運行了你的代碼,我看到了你的問題。您應該使用'ReadLine'替換您的呼叫'Read',並將確認類型更改爲字符串並進行比較。

原因是Console.Read只有在你點擊'enter'時纔會返回,所以它讀取3個字符; '''\ 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; 
} 
+0

謝謝RJ先生! – Kornel