如何实现错误检查

时间:2015-03-06 18:28:43

标签: c#

大家好我有这个应用程序根据列表框中的项目进行打印。 将这些项目与目录中的项目进行匹配:\ slim \ slimyyyy 我想提出一个" ERROR CHECKING"这会给我一个消息,在项目中 目录中不存在列表框中。 例如,如果有8个或更多项不在所述目录中,则给出不在目录中的项目的消息。 下面是我的代码,但我的尝试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");
        }
    }>

1 个答案:

答案 0 :(得分:-1)

这是新的解决方案:   - 请将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.
    }
}