我有一个方法,该方法获取excel文件的路径并打开它。
我不想键入整个文件路径(比如“C:\Users.”),而是希望能够键入"test.csv“,并让程序访问当前目录中的csv文件。
原因是,如果我希望压缩该项目并将其发送给其他人,我希望其他人能够运行它,并看到与我所做的相同的结果,而不必在他们的C:\驱动器中的某个地方手动创建excel文件。
我使用以下代码来检查路径是否存在:
if (System.IO.File.Exists(path))但是,我无法确定哪个目录是默认目录,因此我可以说‘test.csv’。
编辑:我将excel文件放在bin\Debug目录中(其中包含大量.dll和.exe文件),但是方法调用仍然抛出一个找不到该文件的错误。我得到了以下错误:"COMException未被处理--无法找到'test.csv‘。“单击“查看详细信息”时,会看到"System.Runtime.InteropServices.COMException".
编辑2:下面是我在方法中的内容:
appExcel = new Microsoft.Office.Interop.Excel.Application();
if (System.IO.File.Exists(path))
{
aWorkbook = appExcel.Workbooks.Open(path, true, true);
aWorkSheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
}
else
{
Console.WriteLine("Unable to open file");
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
}程序在未处理的aWorkbook= appExcel.Workbooks.Open(path,true,true)行处停止。
发布于 2014-06-26 21:07:40
要获得当前目录路径,可以使用Directory.GetGetCurrentDirectory()。
此外,您还可以通过Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),找到程序集的位置,然后使用该路径作为基本路径。
例如,对于位于程序集旁边的file.csv,可以使用以下方法:
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string filePath = Path.Combine(basePath, "file.csv");https://stackoverflow.com/questions/24440001
复制相似问题