我写的是Windows手机。我的应用程序必须下载图像并将其设置为锁定屏幕,但有时在将图像加载到应用程序存储中并尝试将其设置在锁定屏幕上会引发异常:
该进程无法访问该文件,因为它正在被使用 另一个过程。
但是在安装锁定屏幕之前我关闭了所有流。 我的代码下载:
//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;
}