我是c#的新手,我正在做一个窗口表单程序,以检查excel文件是否存在。如果存在,则需要验证 excel 文件是否已损坏,但我不知道如何编写代码。我完成的搜索Excel文件的部分。#
int point = 0;
if (File.Exists(path1[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Tranfser Error");
point = 1;
}
else
{
for (int x = 1; x < path1.Length; x++)
{
if (File.Exists(path1[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Error");
point = 1;
}
}
}
if (File.Exists(path2[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
else
{
for (int x = 1; x < path2.Length; x++)
{
if (File.Exists(path2[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
}
}
if (File.Exists(path3))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Havent Transfer");
point = 1;
}
if (point == 0)
{
MessageBox.Show("No File of the date "+ Year +"-"+ Month +"-"+ Day);
}
看起来您需要检查多个路径的存在和文件格式? 如果是这样,请以更好的方式构建您的代码。但是,以下函数将为您提供预期的结果。这使用 EPPlus 库,通过 nuget 安装它。
enum ExcelFileTestResult
{
FileNotFound,
ValidFormat, //File found, valid excel
InvalidFormat //File found but not valid excel
}
public static ExcelFileTestResult CheckExcelFile(string path)
{
ExcelFileTestResult result = ExcelFileTestResult.FileNotFound;
if (File.Exists(path))
{
FileInfo fi = new FileInfo(path);
try
{
// Trying to read file using EPPlus
// if the file is not valid format, it will throw error
using (ExcelPackage p = new ExcelPackage(fi))
{
result = ExcelFileTestResult.ValidFormat;
}
}
catch (InvalidDataException ex)
{
result = ExcelFileTestResult.InvalidFormat;
}
}
return result;
}
注意:EPPlus 仅适用于 xlsx,不适用于 xls。https://github.com/JanKallman/EPPlus