I am working on a small UWP app that will take pictures and video and save it at a desired location on the PC.
Here is the code base I am using https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/CameraStarterKit/cs/MainPage.xaml.cs
When I try to initialize StorageFolder class with a desired path, it comes out as null. It only supports to initialize with following paths
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Documents);
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music);
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
Here is my code:
private StorageFolder _captureFolder = null;
_captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
var file = await _captureFolder.CreateFileAsync("SmartPhoto.jpg",
CreationCollisionOption.GenerateUniqueName);
var picturesLibrary = await Task.Run(() =>
System.IO.File.Move(file.Path, #"C:\Temp\Pictures\" + file.Name));
Since StorageFolder is not initializing for C:\Temp\Pictures, I tried to move that file from KnownLibraryId.Pictures to C:\Temp\Pictures and that fails too,
System.UnauthorizedAccessException: 'Access to the path
'C:\Temp\Pictures' is denied.'
This is by design, an UWP app can not - by default - access all locations on your hard drive...
It only has a specific set of folders allowed, but you can enable more by using the file picker or adding capabilities.
As mentioned in the docs here : https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions
Universal Windows Apps (apps) can access certain file system locations
by default. Apps can also access additional locations through the file
picker, or by declaring capabilities.
Related
I want to create a folder named "TestFolder" on local folder of my uwp app. And need to upload files to it. It works fine on my system when I first manually create a folder((TestFolder) on local folder. but when I create app package for the project and tried to run it in another windows pc. It throws an error "System cant find the file specified". How can I resolve it?
StorageFolder appFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("TestFolder");
if (appFolder == null)
{
//Create folder
appFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("TestFolder");
}
i would replace this few lines by this single line
var appFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("TestFolder", Windows.Storage.CreationCollisionOption.OpenIfExists);
You can modify your code this way to get your desired result,
StorageFolder appFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("TestFolder");
if (appFolder == null)
{
//Create folder
appFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("TestFolder",CreationCollisionOption.OpenIfExists);
}
I am creating files and folders using DownloadsFolder methods.
I'd like to get the parent folder as a StorageFolder instance so I can list and manipulate all the items in the app's downloads folder.
I've tried GetParentAsync() from a known StorageFile, but the return is null.
StorageFile sf = await DownloadsFolder.CreateFileAsync("testMarker");
StorageFolder dlFolder = await sf.GetParentAsync();
Is there any method to access this folder programmatically?
It seems your app doesn't has permission to read the Downloads directory. We can use GetParentAsync to get a parent the app has permissions for, but not to get folders the app doesn't have permissions in.
If we add the Music Library, Pictures Library and Videos Library to the Capabilities of the appxmanifest that we can use the GetParentAsync method to get the parent folder as a StorageFolder in these folder.
If you create a file or folder in the Downloads folder, we recommend that you add that item to your app's FutureAccessList so that your app can readily access that item in the future.
For more info, please refer the Locations Windows Store apps can access.
So if you want to get the other folders and files in DownloadsFolder, you should be able to Open files and folders with a picker.
It looks like this isn't possible - You can try to get the storage folder by using the Path with System.IO directly like so
var downloadPath = System.IO.Path.GetDirectoryName(storageFile.Path);
var downloadsFolder = await StorageFolder.GetFolderFromPathAsync(downloadPath);
But GetFolderFromPathAsync seems to throw an exception, I think windows just won't give you a reference to this folder.
A solution is to use a folder picker ONCE to pick the downloads folder (as part of the inital setup of the app). After that the app has full access to the downloads folder.
This code needs to be called once:
var folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
// Application now has read/write access to all contents in the picked folder
// (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.
FutureAccessList.AddOrReplace("DownloadFolderToken", folder);
var messageDialog = new MessageDialog("Download folder: " + folder.Name);
await messageDialog.ShowAsync();
}
else
{
var messageDialog = new MessageDialog("Operation cancelled");
await messageDialog.ShowAsync();
}
This code can then be used to directly access the downloads folder:
var downloadsFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("DownloadFolderToken");
IReadOnlyList <StorageFile> fileList = await downloadsFolder.GetFilesAsync();
StringBuilder outputText = new StringBuilder();
outputText.AppendLine("Files:");
foreach (StorageFile file in fileList)
{
outputText.Append(file.Name + "\n");
await file.DeleteAsync();
}
I'm currently having trouble finding out how to implement isolated storage in a windows universal project.
All I want to do is safe some text in isolated storage when a button is clicked and the be able to retrieve it later on a different page for use.
You can use ApplicationData.Current.LocalSettings as a dictionary where you can save some primitive object.
ApplicationData.Current.LocalSettings.Values["MyKey"] = MyValue;
if (ApplicationData.Current.LocalSettings.Values.ContainsKey("MyKey"))
MyValue = ApplicationData.Current.LocalSettings.Values["MyKey"];
You can store your app data locally in UWP, e.g. ApplicationData.Current.LocalFolder, and this is 'Isolated storage' what you are talking about. Here is a code sample for you:
//Create dataFile.txt in LocalFolder and write “My text” to it
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt");
await FileIO.WriteTextAsync(sampleFile, "My text");
//Read the first line of dataFile.txt in LocalFolder and store it in a String
StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
String fileContent = await FileIO.ReadTextAsync(sampleFile);
You can also see here for more details: Getting started storing app data locally
I am in trouble with some issue about FileSavePicker. Is there any solution about saving a StorageFile without showing any popup or dialog to ask user. I want to give the current path of the storage file from code behind.
var byteArray = Convert.FromBase64String(Base64);
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("file.jpg", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteBytesAsync(file, byteArray);
var savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add("JPEG-Image", new List<string>() { ".jpg" });
savePicker.SuggestedSaveFile = file;
savePicker.PickSaveFileAsync();
...We have to use a few paths which are defined under
'Windows.Storage.KnownFolders'...
it is not so. In fact your app can access any folder on device but it will need additional permissions. The most straightforward way to obtain permission you should do next:
1) ask user to pick folder from FolderPicker
2) store selected folder to StorageApplicationPermissions.FutureAccessList
After this your app can do anything with this folder.
Code that demonstrate how to obtain permissions:
var picker = new FolderPicker();
var pfolder = await picker.PickSingleFolderAsync();
StorageApplicationPermissions.FutureAccessList.Add(pfolder);
Code that demonstrate how to create file in desired folder:
var folder = await StorageFolder.GetFolderFromPathAsync("your path");
var file = await folder.CreateFileAsync("text.txt");
using (var writer = await file.OpenStreamForWriteAsync())
{
await writer.WriteAsync(new byte[100], 0, 0);
}
But keep in mind that "your path" is folder or any of subfolder that was stored to StorageApplicationPermissions.FutureAccessList. More details here FutureAccessList
StorageFile.GetFileFromPathAsync() is probably what you are looking for. I think the file must be created beforehand for this method to work. Be aware that creating the file in some locations might need additional permissions or is even impossible (I don't know how UWP and UAC interact).
Another possibility is to use Win32 APIs inside UWP apps. Maybe this can solve your problem if the desired API is available.
I want to thank you all for your interest. I figured out the solution. If you do not want to use any dialog or prompting you can not use FileSavePicker. Here are the simple codes you need to converting Base64 string to image and save.
var byteArray = Convert.FromBase64String(Base64);
StorageFile file = await Windows.Storage.KnownFolders.SavedPictures.CreateFileAsync(
"file.jpg", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteBytesAsync(file, byteArray);
I guess there is no way to give specific path. We have to use a few paths which are defined under Windows.Storage.KnownFolders. If it is not, please give some information about it.
Wow, is this way more complicated than it needs to be. Can someone explain to me why the following code works:
string stringToWrite = "SomeStuff";
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
var files = await installedLocation.GetFilesAsync();
foreach (Windows.Storage.StorageFile sf in files)
{
if (sf.Name.Equals("log.txt"))
{
await FileIO.AppendTextAsync(sf, stringToWrite);
}
}
And yet the following fails with AccessDenied:
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
var log = await installedLocation.GetFileAsync("log.txt");
await FileIO.AppendTextAsync(log, stringToWrite);
The only difference is looping through the files returned by the GetFilesAsync method vs getting the file by name. By the way, getting the file by name works because if I misspell log.txt in GetFileAsync, I get an exception.
Very confusing....
You should not be using your installed location to write any files. It is supposed to be read-only as per MSDN: File Access/Permissions in Windows Store Apps:
The app's install directory is a read-only location. You can’t gain access to the install directory through the file picker.
You should be using either the Local, Roaming, or Temporary storage locations.
See this link: MSDN: Quickstart Local Application Data