简体   繁体   中英

uwp unable to save file

I'm trying to save a file to the application storage using these methods (when the app is running):

First I create the file from an URI:

StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri));

Then I copy the file to the app's storage to be able to use it later:

StorageFile file2 = await file.CopyAsync(ApplicationData.Current.LocalFolder, name, NameCollisionOption.ReplaceExisting);

But the second method CopyAsync() does not finish and then randomly fails with this error after waiting ~5min:

错误截图 .

Also, processes are added in the app's lifecycle every time I call t he CopyAsync() method:

生命周期过程 .

When I click on one of the processes, the CopyAsync() method ends.

To solve this issue I have to reboot my phone and uninstall/install the app.

NOTE: When I try this in a background task this fail 100% of the time.

I was able to solve the issue thanks to this post

And the code works in a background task as well :)

This does not explain why the FileStorage.CopyAsync() method fails, but it's a workaround until someone gets more information.

(It seems when CopyAsync() fails in a background task it will block any futur call to this method in a background task or in the foreground app)

The code snippet:

 private async Task<StorageFile> DownloadImagefromServer(string URI, string filename) {
        filename += ".png";
        var rootFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Citations365\\CoverPics", CreationCollisionOption.OpenIfExists);
        var coverpic = await rootFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);

        try {
            HttpClient client = new HttpClient();
            byte[] buffer = await client.GetByteArrayAsync(URI); // Download file
            using (Stream stream = await coverpic.OpenStreamForWriteAsync())
                stream.Write(buffer, 0, buffer.Length); // Save

            return coverpic;
        } catch {
            return null;
        }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM