获取资源文件夹路径 c#

13

我的项目中有一些资源使用字符串路径可以正常工作,但如果我将项目移动到另一个目录或另一台计算机上,它将停止工作。

请帮我获取项目资源文件夹的路径,并存储在一个字符串变量中,例如:

C:\Users\User1\Documents\<projects folder>\<project name>\Resources\

提前致谢。


1
你如何在代码中访问资源? - crea7or
@crea7or 我只是使用我的项目路径,例如:pictureBox1.ImageLocation = @"C:\Users\Isaac\OneDrive\Proyectos\Proyecto Final Solucion\BD Clases\Proyecto Final\Resources\Terreno\0.jpg"; 来在PictureBox中显示一张图片。 - Isaac Tuncar Cedron
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 返回路径 C:\Users\Isaac\Documents,然后你可以将其与你的文件夹的后半部分连接起来。 - kennyzx
4个回答

19

如果您知道相对于应用程序运行位置的路径,可以像这样操作。 首先,获取应用程序的运行路径:

string RunningPath = AppDomain.CurrentDomain.BaseDirectory;

然后,使用类似以下方式导航到相对路径:

string FileName = string.Format("{0}Resources\\file.txt", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\")));

在这个例子中,我的“资源”文件夹位于当前文件夹的两级目录上方。

我还应该提到,如果您的资源已包含在项目中,则应该能够使用以下方式获取它:

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

这将返回您资源的数组。


我使用 GetManifestResourceNames(); 方法,但它只返回 MyProject.g.resourcesMyProject.Properties.Resources.resources... 为什么会发生这种情况? - Uchiha Itachi

14
如果文件存储在您的项目文件夹中,您可以使用System.AppDomain.CurrentDomain.BaseDirectory来检索这些文件。此语句检索应用程序安装位置的路径。单击此处获取有关此内容的详细说明。

3

这可能不是最优雅的方式,但对我很有用。

如果你拥有一个如下结构的东西:

C:\...\MyApp\app.exe
C:\...\MyApp\ConfigFiles\MyConfig.xml

该代码将返回与运行程序集相关的路径。
GetPath("ConfigFiles/MyConfig.xml") // returns the full path to MyConfig.xml

private string GetPath(string relativePath)
{
    var appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    string pattern = @"^(.+\\)(.+exe)$";
    Regex regex = new Regex(pattern, RegexOptions.None);
    var match = regex.Match(appPath);
    return System.IO.Path.GetFullPath(match.Groups[1].Value + relativePath);
}

0

你可以尝试使用在这里文档化的|DataDirectory|。

以下是来自一篇旧的微软文章的工作原理描述。

One of the reasons why it was hard to work with database files before is that the full path to the database was serialized in different places. This made it harder to share a project and also to deploy the application. In this version, the .NET runtime added support for what we call the DataDirectory macro. This allows Visual Studio to put a special variable in the connection string that will be expanded at run-time. So instead of having a connection string like this:

  "Data Source=.\SQLExpress;AttachDbFileName=c:\program files\app\data.mdf"

You can have a connection string like this:

  "Data Source=.\SQLExpress;AttachDbFileName=|DataDirectory|\data.mdf"

This connection string syntax is supported by the SqlClient and OleDb managed providers.

By default, the |DataDirectory| variable will be expanded as follow:

  - For applications placed in a directory on the user machine, this will be the app's (.exe) folder.
  - For apps running under ClickOnce, this will be a special data folder created by ClickOnce
  - For Web apps, this will be the App_Data folder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接