How to avoid StorageFile.CopyAsync () exception when copying a large file?

I am going to copy some files from the video library to the application store via the StorageFile.CopyAsync() method, but if the file size exceeds 1 GB, it throws an exception as follows:

Type: System.Runtime.InteropServices.COMException Message: Error HRESULT E_FAIL was returned from a call to the COM component. Stacktrace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task task) in System.Runtime.CompilerServices.ultaskaTr

How to import a large file, is there a solution to solve this problem?

+6
source share
2 answers

I would try to copy it through a buffer - for example, like this:

 private async Task CopyBigFile(StorageFile fileSource, StorageFile fileDest, CancellationToken ct) { using (Stream streamSource = await fileSource.OpenStreamForReadAsync()) using (Stream streamDest = await fileDest.OpenStreamForWriteAsync()) await streamSource.CopyToAsync(streamDest, 1024, ct); return; } 
+5
source

I am writing an extension method, it solved my problem, you can refer to it when you need the following:

 public static class FileExtentions { #region Fields private static readonly ulong MaxBufferSize = 16 * 1024 * 1024; #endregion // Fields #region Methods public static async Task<StorageFile> CopyAsync(this StorageFile self, StorageFolder desiredFolder, string desiredNewName, CreationCollisionOption option) { StorageFile desiredFile = await desiredFolder.CreateFileAsync(desiredNewName, option); StorageStreamTransaction desiredTransaction = await desiredFile.OpenTransactedWriteAsync(); BasicProperties props = await self.GetBasicPropertiesAsync(); IInputStream stream = await self.OpenSequentialReadAsync(); ulong copiedSize = 0L; while (copiedSize < props.Size) { ulong bufferSize = (props.Size - copiedSize) >= MaxBufferSize ? MaxBufferSize : props.Size - copiedSize; IBuffer buffer = BytesToBuffer(new byte[bufferSize]); await stream.ReadAsync(buffer, (uint)bufferSize, InputStreamOptions.None); await desiredTransaction.Stream.GetOutputStreamAt(copiedSize).WriteAsync(buffer); buffer = null; copiedSize += (bufferSize); Debug.WriteLine(DeviceStatus.ApplicationCurrentMemoryUsage); } await desiredTransaction.CommitAsync(); return desiredFile; } private static IBuffer BytesToBuffer(byte[] bytes) { using (var dataWriter = new DataWriter()) { dataWriter.WriteBytes(bytes); return dataWriter.DetachBuffer(); } } #endregion // Methods 
+1
source

Source: https://habr.com/ru/post/969848/


All Articles