c#功能在内部,而不是循环

时间:2014-12-23 11:45:16

标签: c# while-loop

大家好,我有这个代码

StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line = reader.ReadLine();
string app = "";
int i = 0;

while (line != null)
{
   i++;
   line = reader.ReadLine();
   if (line != null)
   {
       int lunghezza = line.Length;
   }

   Console.WriteLine(i);
   System.Threading.Thread.Sleep(800);
   string ris= traduttore.traduci(targetLanguage, line);

   // Console.WriteLine(line);
   // Console.WriteLine(ris);
   // Console.Read();
   // app = app + ris;

   // System.Threading.Thread.Sleep(50);

   File.AppendAllText(@"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}

事实是我有一个txt文件,我想用这个函数traduci(targetLanguage,line)进行翻译,函数没问题,我想把每一行翻译成另一个文件,而循环函数是阻塞的第一个循环,如果我插入consonle.read()当我按下输入功能工作...我可以吗?谢谢大家!

3 个答案:

答案 0 :(得分:1)

你的代码非常混乱。我建议使用以下方法遍历StreamReader行:

        using (StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt"))
        {
            string line;

            while (!reader.EndOfStream)
            {
                line = reader.ReadLine();

                // ... process the line
            }
        }

答案 1 :(得分:0)

如果ReadLine返回null,则代码将中断。更好的结构:

StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line;
string app = "";
int i = 0;

while ((line = reader.ReadLine()) != null)
{
   i++;
   int lunghezza = line.Length;

   Console.WriteLine(i);
   System.Threading.Thread.Sleep(800);
   string ris= traduttore.traduci(targetLanguage, line);

   // Console.WriteLine(line);
   // Console.WriteLine(ris);
   // Console.Read();
   // app = app + ris;

   // System.Threading.Thread.Sleep(50);

   File.AppendAllText(@"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}

答案 2 :(得分:0)

现在的代码会跳过第一行,因为您在第一次使用之前会使用ReadLine()两次。

您可以将代码重组为

using (StreamReader reader = new StreamReader(@"C:\Users\lorenzov\Desktop\gi_pulito_neg.txt"))
using (StreamWriter writer = new StreamWriter(@"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt"))
{

    string line = reader.ReadLine();
    while(line != null)
    {
       System.Threading.Thread.Sleep(800);
       string ris = traduttore.traduci(targetLanguage, line);

       writer.WriteLine(ris);

       line = reader.ReadLine();
    }

}