当我尝试删除文件夹时,出现以下错误:
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
整个代码块在这里:
StorageFolder folder;
try
{
folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("images");
await folder.DeleteAsync();
StorageFolder new_images = await ApplicationData.Current.LocalFolder.CreateFolderAsync("images", CreationCollisionOption.ReplaceExisting);
}
catch (FileNotFoundException ex)
{
StorageFolder new_images = await ApplicationData.Current.LocalFolder.CreateFolderAsync("images", CreationCollisionOption.ReplaceExisting);
}
此行发生错误:
await folder.DeleteAsync();
当我从images文件夹中添加一堆图像时,我猜这个问题就出现了:
tmp.Source = new BitmapImage(new Uri("ms-appdata:///local/images/image_" + ring.Name + ".jpg", UriKind.Absolute));
也可能是我保存图片的时候:
try {
StorageFile file = await image_folder.CreateFileAsync("image_" + id + ".jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, responseBytes);
} catch (System.Exception)
{
}
如果问题出现是因为它正在阅读它并且我尝试删除该文件夹,我怎么能让它工作,老实说我不知道该怎么做。
答案 0 :(得分:1)
抛出异常:mscorlib.ni.dll中的'System.UnauthorizedAccessException'
我注意到您尝试使用FileIO.WriteBytesAsync()方法保存图像,我无法看到如何将图像文件加载到Byte数组。最可能的原因是“在打开它以加载图像数据后忘记丢弃流”
这是我加载图片并保存到LocalFolder的方式:
private async Task<byte[]> ConvertImagetoByte(StorageFile image)
{
IRandomAccessStream fileStream = await image.OpenAsync(FileAccessMode.Read);
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
return pixels;
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
var uri = new Uri("ms-appx:///images/image.jpg");
var img = await StorageFile.GetFileFromApplicationUriAsync(uri);
byte[] responseBytes = await ConvertImagetoByte(img);
var image_folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("images", CreationCollisionOption.OpenIfExists);
StorageFile file = await image_folder.CreateFileAsync("image_test.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, responseBytes);
tmp.Source = new BitmapImage(new Uri("ms-appdata:///local/images/image_test.jpg", UriKind.Absolute));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
答案 1 :(得分:0)
这可能听起来很奇怪,但有时我们不会以管理员身份启动IDE时会出现授权类型的问题。通过右键单击IDE(Visual Studio)图标,然后选择“以管理员身份运行”来完成此操作。
如果能解决您的问题,请尝试此操作。
答案 2 :(得分:0)
您需要使用lock
以确保在其他线程中使用时不会修改文件或文件夹。由于您正在使用等待,我建议您查看一下 - https://github.com/bmbsqd/AsyncLock/
您可以在此处获取有关线程同步的更多信息 - https://msdn.microsoft.com/ru-ru/library/ms173179(v=vs.80).aspx