如何实现错误检查

本文关键字:错误 检查 实现 何实现 | 更新日期: 2024-10-20 00:41:49

大家好,我有一个应用程序,可以根据列表框上的项目进行打印。通过将这些项目与以下目录中的项目进行通信:''slim''slimyyyy我想放一个"错误检查",它会给我一个消息列表框上的不在目录中。例如,如果有8个或更多项目不在所述目录中,则用不在目录中的项目发出消息。下面的Find是我的代码,但我的try-catch没有任何作用。欢迎任何帮助提前谢谢。

{
        //var printList = new List();
        try
        {
            var printList = new List();
            string dir = @"C:'slim'slimyyyy";
            if (Directory.Exists(dir))
            {
                string[] pdf_specFiles = Directory.GetFiles(dir);
                if (pdf_specFiles.Length > 0)
                {
                    foreach (object item in listBox1.Items)
                    {
                        foreach (string file in pdf_specFiles)
                        {
                            string fileName = Path.GetFileName(file);
                            if (fileName == item.ToString())
                            {
                                printList.Add(Path.GetFullPath(file));
                            }
                        }
                    }
                    foreach (string file in printList)
                    {
                        PrintDocument(file);
                        System.Threading.Thread.Sleep(10000); // wait 10 second say
                        Application.DoEvents(); // keep UI responsive if Windows Forms app
                    }
                }
            }
        }
        catch (Exception)
        {
            MessageBox.Show("You are missing Item(s).", "ERROR");
        }
    }>

如何实现错误检查

以下是新的解决方案:-请将using System.Linq放在表格的顶部

private void Form1_Load(object sender, System.EventArgs e)
{
    const string directoryPath = @"C:'slim'slimyyyy";
    var printList = new List<string>();
    foreach (string item in listBox1.Items)
    {
        var currentFilePath = Path.Combine(directoryPath, item);
        if (File.Exists(currentFilePath))
        {
            printList.Add(item);
        }
    }
    if (!printList.Any())
    {
        MessageBox.Show("File doesn't exist");
        return;
    }
    foreach (string file in printList)
    {
        PrintDocument(file);
        // Why you want to wait?? Let it print.
    }
}