C# 函数内部 虽然不会循环
本文关键字:循环 函数 内部 | 更新日期: 2023-09-27 18:35:02
大家好,我有这个代码
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(( 函数工作...我能做什么吗?谢谢大家!
你的代码很混乱。我建议使用以下方法来循环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
}
}
如果 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);
}
代码将跳过第一行,因为您在使用拳头之前使用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();
}
}