Search code examples
c#winformslinqcheckboxsystem.diagnostics

How to Compare Listbox item(s) with Array Items


I have one check box which contains some exe/application names. When i am going to select any one of them then it should start. Now application is starting but if i have selected exe/application name from check box which does not exists in path(which i have written below), i.e. how to put validation on that. My code is:

if (chkListBox.CheckedItems.Count > 0)
{
    for (int i = 0; i < chkListBox.CheckedItems.Count; i++)
    {
        string path = @"D:\Development\Latest\ConsoleApplication1\ConsoleApplication1\bin\Debug";
        string files = Directory.GetDirectoryRoot(path);
        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = Path.Combine(path, chkListBox.Items[i].ToString() + ".exe")
            }
        };

        process.StartInfo.UseShellExecute = false;// Beacuse I  am using Process class
        process.StartInfo.CreateNoWindow = true;
        process.Start();
    }
}
else
{
    MessageBox.Show("Item Not  selected");
}

Solution

  • string path = @"D:\Development\Latest\ConsoleApplication1\ConsoleApplication1\bin\Debug";
    string files = Directory.GetDirectoryRoot(path);
    
    var exeNotFoundList = new List<string>();
    
    for (int i = 0; i < chkListBox.CheckedItems.Count; i++)
    {
        var exeFilePathWithName = Path.Combine(path, chkListBox.Items[i].ToString() + ".exe");
        if(!File.Exists(exeFilePathWithName))
        {
             exeNotFoundList.Add(exeFilePathWithName);
             continue;
        }
        var process = new Process
            {
                StartInfo = new ProcessStartInfo
                   {
                      FileName = exeFilePathWithName
                    }
             };
    
       process.StartInfo.UseShellExecute = false;// Beacuse I  am using Process class
       process.StartInfo.CreateNoWindow = true;
       process.Start();
    
    }
    
    if(exeNotFoundList.Count > 0)
    {
        var errorMessage = String.Join(String.Empty, exeNotFoundList.ToArray());
        MessageBox.Show(errorMessage);
    }