I have an image file I get from the picker. I save it as 'me.png' in:
Windows.Storage.ApplicationData.Current.LocalFolder
If I perform the action again to try to overwrite the old file with a new one the app crashes with:
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
If there is a handler for this exception, the program may be safely continued.
The code I'm using to overwrite the file is:
await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, "me.png", Windows.Storage.NameCollisionOption.ReplaceExisting);
Any idea why this is happening? It's crashing on that line of code second time round. If I change the collision option to GenerateUniqueName it works fine so it seems to be a problem overwriting the file.
Update:
Full code
localSettings.Values["me_image_path"] = "Asssets/pinkBackground.png";
tile.BackgroundImage = localSettings.Values["me_image_path"];
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
if (file == null) return;
await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, "me.png", Windows.Storage.NameCollisionOption.ReplaceExisting);
localSettings.Values["me_image_path"] = "ms-appdata:///local/me.png";
tile.BackgroundImage = localSettings.Values["me_image_path"];
Related
Now I am working on edit operation in my app. So in edit operation there is an ability to change image and in the same time name of the file that keep image of the contact can not be renamed(during one session of operation image files will be changing but all this file will take same name).
And I used overload of CopyAsync method (docs to this method here) that as I have understand must to replace file to the existing file with the same name.
I get imageFile variable by FileOpenPicker. Code below runs every time I have choosed image by FileOpenPicker. And when I re-choose image at the result Image UI control show me previous chosen image. I expect that Image will view last image that I have choosed but this does not occurred.
public BitmapImage Image { set; get; }
//Copy of the file that saved in temporary storage
StorageFile fileForView = await imageFile.CopyAsync
(ApplicationData.Current.TemporaryFolder,
fileName,
NameCollisionOption.ReplaceExisting);
Image = new BitmapImage(new Uri(fileForView.Path));
Maybe I understand logic of CopyAsync method not correctly if I am in this case please show me how make my plan working with this method if it is possible. Otherwise offer your solution cause I have no idea now how to do this.
Also I tried to do this with CopyAndReplaceAsync method. But still no result. I do it in this way:
if (null != await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(fileName))
{
StorageFile storageFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(fileName);
await storageFile.CopyAndReplaceAsync(imageFile);
}
I expect that Image will view last image that I have choosed but this does not occurred.
The above CopyAsync method is correct, and I have tested with the following code, it works well.
private async void ListOption_ItemClick(object sender, ItemClickEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
StorageFile fileForView = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.ReplaceExisting);
Image = new BitmapImage(new Uri(fileForView.Path));
TestImg.Source = Image;
}
else
{
}
}
I want to open a text file with Open File Picker and show in a RichEditBox, but when I select the file and push Ok, Visual Studio show "Access Denied", I want to know how to solve this please, there is my code:
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeFilter.Add("*");
picker.FileTypeFilter.Add(".txt");
picker.FileTypeFilter.Add(".text");
picker.FileTypeFilter.Add(".bat");
picker.FileTypeFilter.Add(".js");
picker.FileTypeFilter.Add(".vbs");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile filepath = await StorageFile.GetFileFromPathAsync(file.Path);
string text = await FileIO.ReadTextAsync(filepath);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
You don't need to call StorageFile.GetFileFromPathAsync(file.Path) since you already have this StorageFile in the file variable returned from PickSingleFileAsync:
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
string text = await FileIO.ReadTextAsync(file);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
The unnecessary GetFileFromPathAsync probably throws an AccessDenied error since the FileOpenPicker provides access only through the returned StorageFile and doesn't give direct access to the file through its path. This behavior is version dependent and new versions of Windows 10 will allow more direct access through file system API (see the Build 2017 talk UWP Apps file access improvements
My windows8.1 store app needs to open word Document and pdf file in read only format from the customized path folder not in Assest.
Code below
Encoding utf8 = new System.Text.UTF8Encoding(true, true);
StorageFolder storagefolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile storagefile = await storagefolder.GetFileAsync(#"C:\sampledoc\sample_raw.txt");
var options = new Windows.System.LauncherOptions() { DisplayApplicationPicker = true };
await Launcher.LaunchFileAsync(storagefile, options);
While running the the above code getting below mentioned Errors
An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
When I try to delete a folder I get the following error:
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
The whole block of code is here:
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);
}
The error occurs on this line:
await folder.DeleteAsync();
I'm guessing the issue comes when I add a bunch of images from the images folder like so:
tmp.Source = new BitmapImage(new Uri("ms-appdata:///local/images/image_" + ring.Name + ".jpg", UriKind.Absolute));
It could also be when I save the image:
try {
StorageFile file = await image_folder.CreateFileAsync("image_" + id + ".jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, responseBytes);
} catch (System.Exception)
{
}
If the issue comes because it is reading it and I try to delete the folder, how can I make it work, I honestly don't know what to do here.
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
I noticed that you were trying to save the image using FileIO.WriteBytesAsync() method, I couldn't see how you load the image file to Byte array. The most possible reason is "forgot to dispose of the stream after opening it to load image data"
This is the way I load an image and save to 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);
}
}
It may sound strange but at times authorization type of issues occur when we don't start our IDE as an administrator. Which is done by right clicking on the IDE (Visual Studio) icon and then select 'Run as Administrator'
Try this if it resolves your issue.
You need to use lock to be sure that file or folder will not be modified while it using in another thread. Since you are using await I would suggest to take a look at this - https://github.com/bmbsqd/AsyncLock/
You can get more info about thread sync here - https://msdn.microsoft.com/ru-ru/library/ms173179(v=vs.80).aspx
I'm making a Windows 10 Universal App and I want the user to pick a folder to save the document files for the App. The path for this folder is saved to ApplicationData.Current.RoamingSettings.Values.
Here's the code:
On first Start:
var folderPicker = new FolderPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder };
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
StorageFolder homeFolder = await folder.CreateFolderAsync("App1 Data", CreationCollisionOption.OpenIfExists);
var save = ApplicationData.Current.RoamingSettings.Values;
save["HomeFolder"] = homeFolder.Path;
When HomeFolder is set:
string dir = save["HomeFolder"].ToString();
try
{
StorageFolder homeFolder = await StorageFolder.GetFolderFromPathAsync(dir);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
The thrown Exception in the second code sample is:
System.UnauthorizedAccessException: access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
So my question is, how do you use the GetFolderFromPathAsync function correctly?
I checked all strings for the paths, they are all right, even
StorageFolder.GetFolderFromPathAsync(storageFolder.Path);
doesn't work.
Do you know a solution?
Use the StorageFile directly rather than converting to a path.
To store the file returned from the file picker for later use save the StorageFile in the AccessCache classes FutureAccessList or MostRecentlyUsedList. The path doesn't include the spermissions needed to open the file. The StorageFile carries the permissions and grants access to the file.
I discussed this in more detail in my blog entry Skip the path: stick to the StorageFile