【问题标题】:Copy file from UWP resources to local folder将文件从 UWP 资源复制到本地文件夹
【发布时间】:2017-05-24 00:32:05
【问题描述】:

我正在尝试将文件从 UWP 资源复制到用户的本地文件夹中。

我能得到的最接近的是:

public static void CopyDatabaseIfNotExists(string dbPath)
{
        var storageFile = IsolatedStorageFile.GetUserStoreForApplication();

        if (storageFile.FileExists(dbPath))
        {
            return;
        }

        using (var resourceStream = Application.GetResourceStream(new Uri("preinstalledDB.db", UriKind.Relative)).Stream)
        {
            using (var fileStream = storageFile.CreateFile(dbPath))
            {
                byte[] readBuffer = new byte[4096];
                int bytes = -1;

                while ((bytes = resourceStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    fileStream.Write(readBuffer, 0, bytes);
                }
            }
        }
    }

但这似乎不再适用于 UWP。 GetResourceStream 不再可用(“应用程序不包含 'GetResourceStream' 的定义”)。

谁能告诉我如何用 UWP 做到这一点?

非常感谢!

【问题讨论】:

    标签: c# uwp


    【解决方案1】:

    您可以简单一点,只需将ApplicationData.Current.LocalFolder 替换为您想要的文件夹即可。

    try
    {
        await ApplicationData.Current.LocalFolder.GetFileAsync("preinstalledDB.db");
        // No exception means it exists
        return;
    }
    catch (System.IO.FileNotFoundException)
    {
    // The file obviously doesn't exist
    }
    
    // Cant await inside catch, but this works anyway
    var storfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///preinstalledDB.db"));
    await storfile.CopyAsync(ApplicationData.Current.LocalFolder);
    

    try 块可能看起来很奇怪,但它实际上是确定文件是否存在的最快方法。

    【讨论】:

    • 谢谢,但我的 void 是 public static void CopyDatabaseIfNotExists(string dbPath)。它不允许 await 运算符。有没有办法使用 await 运算符?
    • 另外,await 是异步的,对吧?这意味着虚空将立即返回,对吗?我不确定这是否真的是我需要的。您能否分享一些关于如何使用您的代码的见解?
    • 是的,您需要使方法异步并等待它。没办法。
    • 但是这个方法有可能只有在我尝试打开数据库之后才能成功,对吧???
    • 旁注:从 C# 6 开始,可以在 catch 中等待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2017-03-31
    • 2016-12-30
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多