Skip to main content
 首页 » 编程设计

C# foreach 带逗号的字符串

2024年02月06日23rubylouvre

我有这个代码:

string[] neededFiles = { 
                           "file1.exe", 
                           "fille2.exe" 
                       }; 
for (int file = 0; file != neededFiles.Length; file++) 
{ 
    if (!File.Exists(neededFiles[file])) 
    { 
        MessageBox.Show("App can't find this file - " + neededFiles[file]); 
        return; 
    } 
} 

现在,当我启动我的应用程序时,它会打印:

App can't find this file - file1.exe

App can't find this file - file2.exe

没关系,但我不想这样:

App can't find this(-these) file(-files) - file1.exe, file2.exe

有什么功能/我该怎么做?是否可以?提前致谢

请您参考如下方法:

// using System.IO; 
// using System.Windows.Forms; 
// using System.Collections.Generics; 
// using System.Linq; 
IEnumerable<string> notFound = neededFiles.Where(f => !File.Exists(f)); 
if (notFound.Any()) 
    MessageBox.Show( 
        string.Format(notFound.Count() > 1 ? 
            "App can't find these files - {0}" : 
            "App can't find this file - {0}", 
        string.Join(", ", notFound)));