【问题标题】:Building full path to file, which is inside a folder inside the directory of the executing program [closed]构建文件的完整路径,该路径位于执行程序目录内的文件夹内[关闭]
【发布时间】:2020-07-26 05:34:29
【问题描述】:

在 .exe 的目录中,有一个名为 exports 的文件夹。我有一个方法,它接受目录和文件名的参数。

在这种情况下,我想将目录作为 exports 文件夹。以下是当前代码:

public void saveFile(string dir, string filename)
{
    ExcelPackage pck = new ExcelPackage();

    // creating a spreadsheet...

    // now save the file
    System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(dir, filename) + ".xlsx");
    pck.Save(file);
    pck.Dispose();
}

// usage of the above method
saveFile(System.Reflection.Assembly.GetExecutingAssembly().Location + @"\exports", "myFileName");

这会产生一个异常:“不支持给定路径的格式”。如何解决?

【问题讨论】:

  • Soo.. 你为什么在方法内部使用 path.combine 而不是在方法外部使用?
  • 我想我只是通过调试结果发现了问题。它实际上是“...\Debug\myApp.exe\exports\myFileName.xlsx”。它包含可执行文件的文件名作为路径的一部分。
  • 检查我的答案的更新顺便说一句,它可能会为您节省接下来的几个头痛!

标签: c# .net fileinfo system.io.file


【解决方案1】:

System.Reflection.Assembly.GetExecutingAssembly().Location 给出文件或 exe 的完整路径,包括 exe 名称

如果不先删除 exe 名称,则无法在其后添加文件夹名称

尝试使用Path.GetDirectoryName 从路径中删除文件名:

var folder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
folder = Path.Combine(folder, "exports");

在尝试将文件写入已构建的文件夹路径之前,Directory.CreateDirectory(folder) 总是一个好主意。如果文件夹存在,它是一个非操作,如果它不存在,那么它将创建它。它可以一次创建多个子文件夹

还请记住,在 Program Files 中正确安装后,应用程序不会自动有权将文件保存到 Program Files 下的子文件夹中。当程序安装到 Program Files 时,您在此处与程序一起保存数据的代码可能会失败

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2016-10-24
    • 1970-01-01
    • 2011-07-22
    相关资源
    最近更新 更多