从应用程序安装文件夹复制文件到本地存储

3

我试图将一个文件从Windows 8应用程序的安装位置复制到它的本地存储。我一直在搜索并尝试做这个事情,但是一直没有成功。目前为止,我想出了以下方法,但我不确定哪里出错了。

    private async void TransferToStorage()
    {


        try
        {
            // Get file from appx install folder
            Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
            Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
            StorageFile temp1 = await installedLocation.GetFileAsync("track.xml");
            // Read the file
            var lines = await FileIO.ReadLinesAsync(temp1);

            //Create the file in local storage
            StorageFile myStorageFile = await localFolder.CreateFileAsync("track_iso.xml", CreationCollisionOption.ReplaceExisting);
            // Write to it
            await FileIO.WriteLinesAsync(myStorageFile, lines);

        }
        catch (Exception)
        {

        }

    }

有什么想法吗?

只是好奇,需要这样做的目的是什么? - A.R.
例如,我有一个XML配置文件模板,我想将其传输到本地存储以便我可以修改它。 - ForeverLearning
哦,我忘记更新/添加注释了。在我提问后不久,我发现为什么要这样做。我有一个默认的设置文件,我将其与安装一起包含,然后复制到本地以保存新设置等。 - A.R.
2个回答

7

我自己解决了这个问题。以下是方法,供其他遇到此问题的人参考:

   private async void TransferToStorage()
    {
        // Has the file been copied already?
        try
        {
            await ApplicationData.Current.LocalFolder.GetFileAsync("localfile.xml");
            // No exception means it exists
            return;
        }
        catch (System.IO.FileNotFoundException)
        {
            // The file obviously doesn't exist

        }
        // Cant await inside catch, but this works anyway
        StorageFile stopfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///installfile.xml"));
        await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);
    }

2
没有必要读取所有行并将其写入另一个文件中,只需使用File.Copy

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