Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何捕获由于在此代码中找不到文件而导致的错误?_C#_Visual Studio 2010 - Fatal编程技术网

C# 如何捕获由于在此代码中找不到文件而导致的错误?

C# 如何捕获由于在此代码中找不到文件而导致的错误?,c#,visual-studio-2010,C#,Visual Studio 2010,我使用此代码在应用程序目录中查找excel文件的名称。但是如果找不到该文件,我想给出一条错误消息。我如何使用c#实现这一点?下面是我用来搜索文件的代码 string linksfile; string [] excelfile = Directory.GetFiles(Application.StartupPath + @"\", "*.xlsx"); linksfile = excelfile[0]; MessageBox.Show(linksfile); 您应该检查if(excelFil

我使用此代码在应用程序目录中查找excel文件的名称。但是如果找不到该文件,我想给出一条错误消息。我如何使用c#实现这一点?下面是我用来搜索文件的代码

string linksfile;
string [] excelfile = Directory.GetFiles(Application.StartupPath + @"\", "*.xlsx");
linksfile = excelfile[0];

MessageBox.Show(linksfile);

您应该检查
if(excelFile.Length>0)

您应该检查
if(excelFile.Length>0)

GetFiles()
将永远不会返回null。如果找不到文件,则在linksfile=excelFile[0]处抛出名为“OndexOutOfRangeException”的异常;我怎样才能克服它呢?我是这样做的,字符串链接文件;字符串[]excelfile=Directory.GetFiles(Application.StartupPath+@“\”,“*.xlsx”);但是,如果(excelfile.Length<0){MessageBox.Show(“未找到调查链接文件!”,“错误”,MessageBoxButtons.OK,MessageBoxIcon.Stop);killprocesss.KillExcelProcess();killprocesss.KillWordProcess();Application.Exit();}否则{MessageBox.Show(linksfile);linksfile=excelfile[0];返回false;},它仍然会给我一个异常MessageBox.Show(linksfile);linksfile=excelfile[0];返回false;您首先访问它,然后分配它。linksfile=excelfile[0];MessageBox.Show(linksfile);返回false;你的代码是正确的!!!!!我的项目文件有问题。现在没事了。感谢
GetFiles()
将永远不会返回null。如果找不到文件,将在linksfile=excelfile[0]处引发名为“OndexOutOfRangeException”的异常;我怎样才能克服它呢?我是这样做的,字符串链接文件;字符串[]excelfile=Directory.GetFiles(Application.StartupPath+@“\”,“*.xlsx”);但是,如果(excelfile.Length<0){MessageBox.Show(“未找到调查链接文件!”,“错误”,MessageBoxButtons.OK,MessageBoxIcon.Stop);killprocesss.KillExcelProcess();killprocesss.KillWordProcess();Application.Exit();}否则{MessageBox.Show(linksfile);linksfile=excelfile[0];返回false;},它仍然会给我一个异常MessageBox.Show(linksfile);linksfile=excelfile[0];返回false;您首先访问它,然后分配它。linksfile=excelfile[0];MessageBox.Show(linksfile);返回false;你的代码是正确的!!!!!我的项目文件有问题。现在没事了。感谢您,我将为权限问题添加一个try/catch。如果未找到文件,将抛出名为“OndexOutOfRangeException”的异常,我如何克服它?但是,我将为权限问题添加一个try/catch。如果未找到文件,将抛出名为“OndexOutOfRangeException”的异常,我如何克服它?
    string linksfile;
    string [] excelfile = Directory.GetFiles(Application.StartupPath + @"\", "*.xlsx");

    if(excelfile.Length > 0)
    {
        linksfile = excelfile[0];

        MessageBox.Show(linksfile);
    }
    else
    {
         MessageBox.Show("File not found");
    }