Dewagg
Dewagg

Reputation: 145

C# foreach string with commas

I have this code:

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

Now when I launch my app it prints :

App can't find this file - file1.exe

App can't find this file - file2.exe

It's ok, but I wan't something like that:

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

With what function / how can I do it? Is it possible? Thanks in advance

Upvotes: 1

Views: 105

Answers (2)

Jashaszun
Jashaszun

Reputation: 9270

// 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)));

Upvotes: 3

Kashif
Kashif

Reputation: 3034

Try this

    string[] neededFiles = {
                                "file1.exe",
                                "fille2.exe"
                           };

    string msg = string.Empty;
    for (int file = 0; file != neededFiles.Length; file++)
    {
        if (!File.Exists(neededFiles[file]))
        {
           msg += neededFiles[file]+" ";
        }
    }
    MessageBox.Show(" App can't find this(-these) file(-files) - " + msg);

Upvotes: 1

Related Questions