簡體   English   中英

如何訪問 WPF 項目中的本地文件夾以加載和存儲文件?

[英]How can I access a local folder inside a WPF project to load and store files?

我需要一個矢量文件庫,每次都必須使用相同的文件。 我想從文件夾中加載它們並可以選擇存儲新的。

我嘗試在 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 上運行時有效,但是當 .exe 在另一台 PC 上運行時程序崩潰。 我該如何解決這個問題,或者有更好的方法來解決這個問題?

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");

感謝喬納森·阿爾法羅克萊門斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM