C# 为什么循环中写入文本文件的行会被写入文本文件这么多次?
如果我不在控制台上放置\r。在没有控制台的情况下编写并使用console.WriteLine,我会在控制台窗口中多次看到此图像[x]文件! 与文本文件中的第二行sw.WriteLine相同,我在那里多次看到它。 我只想看一次,如果文件不存在,显示一次。 为什么它显示的次数如此之多?那我们怎么修呢C# 为什么循环中写入文本文件的行会被写入文本文件这么多次?,c#,C#,如果我不在控制台上放置\r。在没有控制台的情况下编写并使用console.WriteLine,我会在控制台窗口中多次看到此图像[x]文件! 与文本文件中的第二行sw.WriteLine相同,我在那里多次看到它。 我只想看一次,如果文件不存在,显示一次。 为什么它显示的次数如此之多?那我们怎么修呢 谢谢。这是因为您正在测试Y循环中的X文件。将该测试放在外部循环中: if (!File.Exists(images[x])) {
谢谢。这是因为您正在测试Y循环中的X文件。将该测试放在外部循环中:
if (!File.Exists(images[x]))
{
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
}
for(x=0;x
您的内部循环的索引是Y而不是X。因此,您当前所做的是在内部循环的索引X,Y处打印元素-即,为了输出语句的目的,您在X,Y处处理元素,而不是一次
您应该做的是将代码块移动到第二个循环之前。检查X处的文件是否只存在一次就足够了,直到X发生更改。因此,请尝试:
for (x = 0; x < images.Length - 1; x++) {
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x])) {
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
} else {
for (y = x + 1; y < images.Length; y++) {
...
Console.Write(“正在处理文件”+图像[x]+“请稍候”\r);
如果(!File.Exists(图像[x]))
{
Write(“文件“+images[x]+”不存在\r”);
sw.WriteLine(“文件“+images[x]+”不存在”);
}否则{
对于(y=x+1;y
究竟为什么要测试循环中存在的文件?
for (x = 0; x < images.Length - 1; x++) {
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x])) {
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
} else {
for (y = x + 1; y < images.Length; y++) {
...
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x]))
{
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
} else {
for (y = x + 1; y < images.Length; y++)
{
// Etc
}
}