在我的应用程序中,我将位图转换为png并将其存储在文件夹内的文件中。当我第二次尝试再次打开文件时,我会UnauthorisedAccessException
说出"Access is denied"
。
单击“保存”按钮时,将调用以下函数。
private async void SaveClicked(object sender, RoutedEventArgs e)
{
WriteableBitmap wb = new WriteableBitmap(InkCanvas2, null);
Image image = new Image();
image.Height = 150;
image.Width = 450;
image.Source = wb;
await SaveToStorage(wb, image);
TransparentLayer.Visibility = System.Windows.Visibility.Collapsed;
}
SaveToStorage具有以下代码
private async Task SaveToStorage(WriteableBitmap i, Image im)
{
try
{
var dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists);
using (var testpng = await dataFolder.OpenStreamForWriteAsync("testpng.png", CreationCollisionOption.ReplaceExisting))
// HITS EXCEPTION AND GOES TO CATCH BLOCK
{
i.WritePNG(testpng);
testpng.Flush();
testpng.Close();
}
}
catch(Exception e)
{
string txt = e.Message;
}
}
它第一次保存没有错误,第二次,抛出异常。知道为什么会这样吗?
答案 0 :(得分:0)
我想通了!这显然是因为我在尝试打开它之前没有包含文件检查。
我已经重写了这样的代码
IStorageFolder dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists);
StorageFile Ink_File = null;
//Using try catch to check if a file exists or not as there is no inbuilt function yet
try
{
Ink_File = await dataFolder.GetFileAsync("testpng.png");
}
catch (FileNotFoundException)
{
return false;
}
try
{
if (Ink_File != null)
{
using (var testpng = await Ink_File.OpenStreamForWriteAsync())
{
i.WritePNG(testpng);
testpng.Flush();
testpng.Close();
return true;
}
}
}
catch(Exception e)
{
string txt = e.Message;
return false;
}
return false;