C# 如何捕获由于在此代码中找不到文件而导致的错误?
我使用此代码在应用程序目录中查找excel文件的名称。但是如果找不到该文件,我想给出一条错误消息。我如何使用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
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");
}