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

时间:2014-11-14 23:56:13

标签: c# windows

我正在尝试将文件从我的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)
        {

        }

    }

有什么想法吗?

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分:2)

没有理由读取所有行并将其写入另一个文件。只需使用File.Copy