gpt4 book ai didi

c# - Windows UWP C# 删除文件夹

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:47 24 4
gpt4 key购买 nike

当我尝试删除文件夹时出现以下错误:

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();

我猜当我像这样从图像文件夹中添加一堆图像时会出现问题:

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)
{

}

如果问题是因为它正在读取它而我尝试删除该文件夹,我该如何让它工作,老实说我不知道​​该怎么做。

最佳答案

Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll

我注意到您正在尝试使用 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);
}
}

关于c# - Windows UWP C# 删除文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com