【问题标题】:How to find file path after installation of a C# program?安装 C# 程序后如何查找文件路径?
【发布时间】:2020-12-30 01:56:05
【问题描述】:

在另一台计算机上安装程序后,我在查找文件时遇到问题。我正在使用 C#,这是我的代码的一部分:

// template path
string tmpPath = @"|DataDirectory|\Templete.docx";

// output path
string outputName = @"|DataDirectory|\Output.pdf";

// shadow file name
string shadowFile = @"|DataDirectory|\temp.docx";

// Create shadow File
File.Copy(tmpPath, shadowFile, true);

// open word
word.Application app = new word.Application();
Document doc = app.Documents.Open(shadowFile);

我使用"|DataDirectory|",它可以用于查找数据库,但在这里我再次使用它来查找我的 word 文件,它抛出了这个错误:

System.ArgumentException: '路径中有非法字符。'

【问题讨论】:

  • 另外你不应该使用程序目录来存储数据。每个用户都有特定的文件夹供此用途。
  • @JohnnyMopp 那么什么可以帮助我在安装后找到我想要的文件
  • @JohnnyMopp 我在连接字符串中使用它来查找数据库,我认为它也可以使用它
  • @JAlex 安装后我应该用什么来查找文件

标签: c#


【解决方案1】:

您需要为 DataDirectory 创建一个新变量。

string datadirectory = "c:\pathtodatadirectory";

string tmpPath = datadirectory + @"\Templete.docx";
// output path
string outputName = datadirectory + @"\Output.pdf";
// shadow file name
string shadowFile = datadirectory + @"\temp.docx";

您显然希望您的数据目录是动态的。从 OS 变量中获取目录路径。

看到这篇文章。 How can I get the current user directory?

【讨论】:

  • 我更喜欢使用System.IO.Path.Combine() 来处理目录分隔字符的格式问题。
【解决方案2】:

我建议使用带有Assembly.GetEntryAssembly().Location 的反射来获取启动可执行文件的路径。您还可以使用Path 来组合路径和文件名、创建临时文件以及执行其他常见的路径操作。最后,使用Environment.GetFolderPath() 查找我的文档在哪里,或者C:\Users\XXXX\AppData\Local 在哪里以及所有其他特殊命名的文件夹。

using static System.IO.Path;
using static System.Environment;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var template = Combine(path, "Template.docx");
            var tempFile = Combine(GetTempPath(), "temp.docx");
            var userFile = Combine(GetFolderPath(SpecialFolder.LocalApplicationData), "UserPreferences.docx");
            var docFile = Combine(GetFolderPath(SpecialFolder.MyDocuments), "MyDocument.docx");
        }
    }
}

另一种方法是,在安装过程中将程序路径存储在注册表中,然后在程序运行时读取注册表

例如将值写入HKEY_CURRENT_USER\Software\Application1 或任何名称,然后使用Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\Application1") 读取它

【讨论】:

  • 在任务计划程序或 sql server 代理中运行控制台应用程序导致使用 Assembly.GetEntryAssembly().Location 的路径错误。我最终使用它来获得正确的可执行路径: Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
  • GetExecutingAssembly() 是要走的路。剩下的只是文件路径操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 2010-09-17
相关资源
最近更新 更多