【问题标题】:How can I access a local folder inside a WPF project to load and store files?如何访问 WPF 项目中的本地文件夹以加载和存储文件?
【发布时间】:2020-02-03 20:45:43
【问题描述】:

我需要一个矢量文件库,每次都必须使用相同的文件。我想从文件夹中加载它们并可以选择存储新的。

我尝试在 WPF 项目中创建一个包含以下文件的库文件夹: Solution/Project/Library/file1.dxf 我像这样加载它们:

string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(@"\bin\");
var folder = currentDir.Substring(0, cutOff) + @"\Library\";

string[] filePaths = Directory.GetFiles(folder, "*.dxf");

这在构建项目的 PC 上运行时有效,但在另一台 PC 上运行 .exe 时程序崩溃。我该如何解决这个问题或有更好的方法来解决这个问题?

【问题讨论】:

  • 你不需要这些......你所需要的只是文件夹的名称。确保在“CurrentDirectory”中创建文件夹。当应用程序运行时,没有“bin”文件夹......所以一切都将与 .exe 在同一个文件夹中......除非您特别制作它使其位于子文件夹中
  • 请注意,应用程序可能没有对其安装位置文件夹的写入权限,因此前面的注释可能没有用。您通常会在Environment.SpecialFolder.ApplicationDataEnvironment.SpecialFolder.CommonApplicationData 下创建和使用子文件夹。
  • 如果您不需要在该文件夹中保存任何数据,只需将 Visual Studio 项目中文件的Build Action 设置为ContentCopy to Output Directory除了Do not copy.

标签: c# wpf filepath solution storing-data


【解决方案1】:

Environment.SpecialFolder.ApplicationData 下创建一个子文件夹,如果库文件夹中存在,则读取该文件夹中的文件。如果不创建它并将现有的库文件保存到它(这里来自资源):

string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + @"\MyAppLibrary\";

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);

    // Add existing files to that folder
    var rm = Properties.Resources.ResourceManager;
    var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
    foreach (var res in resSet)
    {
        var entry = ((DictionaryEntry)res);
        var name = (string)entry.Key;
        var file = (byte[])rm.GetObject(name);

        var filePath = path + name + ".dxf";
        File.WriteAllBytes(filePath, file);
    }
}

// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");

感谢Jonathan AlfaroClemens

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2018-06-01
    • 2021-02-22
    • 2012-04-04
    相关资源
    最近更新 更多