C#文件异常:另一个进程正在使用该文件

时间:2015-11-18 07:07:28

标签: c# windows-phone

我写的是Windows手机。我的应用程序必须下载图像并将其设置为锁定屏幕,但有时在将图像加载到应用程序存储中并尝试将其设置在锁定屏幕上会引发异常:

  

该进程无法访问该文件,因为它正在被使用   另一个过程。

screenshot

但是在安装锁定屏幕之前我关闭了所有流。 我的代码下载:

    //Download image from server to isolated folder
    public static async Task<StorageFile> DownloadImage(string uri, StorageFolder folder, string fileName)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        try
        {
            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
            if ((response.StatusCode == HttpStatusCode.OK ||
                response.StatusCode == HttpStatusCode.Moved ||
                response.StatusCode == HttpStatusCode.Redirect) &&
                response.ContentType.StartsWith("image/jpeg", StringComparison.OrdinalIgnoreCase))
            {
                StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                using (var streamFrom = response.GetResponseStream().AsInputStream())
                { 
                    using (var streamTo = (await file.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0))
                    {
                        await RandomAccessStream.CopyAndCloseAsync(streamFrom, streamTo);
                    }
                }                   
                return file;
            }
        }
        catch { }
        return null;
    }

0 个答案:

没有答案