C# Downloading And Using File Causes System.UnauthorizedAccessException

大憨熊 提交于 2020-01-14 04:05:50

问题


i'm trying to create an app that downloads a file and then edits this file.

The Problem Im having is once the file is downloaded it doesn't seem to let go of that file, i can download the file to its local storage, i have gotten the file manually from the Iso and its fine. if i use the app to proceed after downloading the file i get the System.UnauthorizedAccessException error, but if i close and open the app and then just edit the file saved in iso it works, like i said its like something is still using the downloaded file.

 public async void DownloadTrack(Uri SongUri)
    {      
        var httpClient = new HttpClient();
        var data = await httpClient.GetByteArrayAsync(SongUri);
        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Test.mp3", CreationCollisionOption.ReplaceExisting);
        var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite);
        await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length);              
        await targetStream.FlushAsync();      

    }

this code works fine to download the mp3, as ive tested the download file. I have seen if examples where the code ends with

targetStream.Close();

but it doesnt give me that, is there another way to close the download thanks.


回答1:


Instead of calling Close() or Dispose() I really like to use using which does the job automatically. So your method could look like this:

public async void DownloadTrack(Uri SongUri)
{
    using (HttpClient httpClient = new HttpClient())
    {
        var data = await httpClient.GetByteArrayAsync(SongUri);
        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Test.mp3", CreationCollisionOption.ReplaceExisting);

        using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length);
            await targetStream.FlushAsync();
        }
    }
}


来源:https://stackoverflow.com/questions/28812827/c-sharp-downloading-and-using-file-causes-system-unauthorizedaccessexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!