Path.GetTempPath() not available in Windows Store Apps - c#

I am trying to get the temp directory by using:
string tempFolder = System.IO.Path.GetTempPath();
However that method does not exist. I can see all the other methods in intelliSense though.
Why is that method not available. Is there another way to get the temp folder location in a Windows Store app?

Create the temporary file in your ApplicatonData storage. You will have to generate your own filename with a guid or timestamp.
Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;
StorageFile sampleFile = await temporaryFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
A Windows Store App is sandboxed, so you are expected to read and write to folders inside your sandboxed application folder. You won't be able to write to the traditional temp folder C:\Windows\TEMP, as you probably want, and yeah you are out of luck. There are a few other locations outside of your application folder that you have access to, but in most cases your access is limited.
The KnownFolders class is how you access the following locations.
CameraRoll
DocumentsLibrary
HomeGroup
MediaServerDevices
MusicLibrary
PicturesLibrary
Playlists
RemovableDevices
SavedPictures
VideosLibrary
KnownFolders class on MSDN

Related

UnauthorizedAccessException when trying to access files

New to C#/VS, trying to get a listing of files, feel like this has a simple answer but can;t find.
Basically, wanting to get a file listing, tried various methods but for simplicity, why does
var f = Directory.GetFiles(#"C:\");
returns
System.UnauthorizedAccessException: 'Access to the path 'C:\' is
denied.'
Tried running VS as administator, tried on sub folders, tried with sub folders having Everyone with full control permission. Same results.
In order to access an arbitrary folder from your UWP app, the user first needs to provide consent via the FolderPicker dialog:
FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
var files = await folder.GetFilesAsync();
https://learn.microsoft.com/en-us/uwp/api/Windows.Storage.Pickers.FolderPicker
System.UnauthorizedAccessException: 'Access to the path 'C:\' is denied.'
Rob has said Windows Store apps run sandboxed and have very limited access to the file system in his blog. Access to other locations is available only through a broker process. This broker process runs with the user’s full privileges.
So you could access the folder that mentioned by Stefan Wick with full privileges FolderPicker.
Apps can access certain file system locations by default. Apps can also access additional locations by declaring capabilities.
There are some locations that all apps can access. Such as InstalledLocation LocalFolder.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
In addition to the default locations, an app can access additional files and folders by declaring capabilities in the app manifest. Such as Pictures Music library.
<Capabilities><uap:Capability Name="musicLibrary"/></Capabilities>
<Capabilities><uap:Capability Name="picturesLibrary"/></Capabilities>
For more, you could refer to File access permissions. And Skip the path: stick to the StorageFile will help you understand uwp file access in depth.

Where to store user-accessible files in UWP?

I have here a cross platform app, which uses DependencyService to get a file path for my log file. This works fine for ApplicationData.Current.LocalCacheFolder.Path, but now the log file should be made accessible to the user. The idea was that the user plugs his device into the PC, copies the log file from it and then send it to me via normal email. (Currently, it is not planned to distribute the app via the store and it is not guaranteed, that the user has an email account setup on his device.)
First, I tried with KnownFolders.DocumentsLibrary, but here I get Access is denied. If I look into the documentation, this folder is not intended for my use. Other locations also doesn't seem to fit.
Is this approach feasible in UWP?
You need to add Capabilities of documentsLibrary to access KnownFolders.DocumentsLibrary
To add go to "Package.appxmanifest" in YourApp.UWP > "Capability" tab and check the capability where you want to store. Example: "Picture Library" or "Removable Storage"
New anser:
I found out, that Access denied only occurs on desktop, not mobile. Afterwards, I found this post, which describes why this does happen. It's because of the permission handling and that I throw away my permissions. There are several possibilites how to handle this situation:
Use a picker to ask the user
Use FutureAccessList
Example:
FolderPicker folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
}
StorageFolder newFolder;
newFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("PickedFolderToken");
await newFolder.CreateFileAsync("test.txt");
Use streams instead of paths (for library)
Make a copy of the file and store it into the application data folder
Example:
StorageFolder tempFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(ApplicationData.Current.LocalCacheFolder.Path, "YourApp"));
StorageFile tempFile = await tempFolder.CreateFileAsync(Path.GetFileName(pathToAttachment), CreationCollisionOption.ReplaceExisting);
await file.CopyAndReplaceAsync(tempFile);
Old answer:
My current solution is that I offer a button in my app, which calls natively the FolderPicker via DependencyService and only on UWP. With this the user can select the location and I copy the file to this location. Works nicely, despite I wish I didn't had to do something only for one platform.

UWP - Get path to user download folder

I have been looking for a little while now and am not finding much help via MSDN resources and others.
My predicament is simple: my app needs a base directory to the Downloads folder. I am aware of the DownloadsFolder class however that is not suiting my needs currently.
How do I get the current user's Download folder path in a Windows Universal App?
Use Windows.Storage.UserDataPaths to get the path of user's download folder.
string downloadsPath = UserDataPaths.GetDefault().Downloads;
This method is introduced in build 16232, so clients with RS3(1709) or later will be able to run it.
You shouldn't obtain downloads folder path using LocalFolder, which might result in wrong folder when the user changed the default location for it.
System.Environment.ExpandEnvironmentVariables("%userprofile%/downloads/")
Is that what you need?
string localfolder = ApplicationData.Current.LocalFolder.Path;
var array = localfolder.Split('\\');
var username = array[2];
string downloads = #"C:\Users\" + username + #"\Downloads";
This will result
C:\Users\username\Downloads
The DownloadsFolder for an app now defaults to a folder withing the user's Downloads directory named after the app name (in actual fact the app name folder is simply a link to a folder named after the Package Family Name)
To get the folder name, I used the following hack (vb) to first create a dummy file in the UWP app's DownloadsFolder then using .NET code to get the directory name, and finally deleting the dummy file.
Dim o As StorageFile = Await DownloadsFolder.CreateFileAsync("dummy.txt", CreationCollisionOption.GenerateUniqueName)
Dim dirName Ss String = Path.GetDirectoryName(o.Path)
Await o.DeleteAsync(StorageDeleteOption.PermanentDelete)

Creating and accessing a folder with in the application for windows phone 8.1

Can some one help me with creating and accessing folder with in the application (at the same place where we have our assets,html folders). My requirement is to download a file in that folder and then access it.
I have used:
StorageFolder destinationFolder = await Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFile localFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.ReplaceExisting);
when I checked it showing the path as: Assets folder path: C:\Data\SharedData\PhoneTools\AppxLayouts\785bb4a5-5b27-4720-918e-7ceaeeb58c52VS.Debug..
If your file saved is not being for any use to end user directly then you should use App local folders. If you have very few amount of data then you can use LocalSettings also. for more available storage options and process of accessing check this link.

Creation of a File

I have created simple UWP application, where I simply want to store serialized data to a file, which can be accessed later (when user reopens the application after a while).
The place, where I want to store the file is the current installed location and my serialization code looks like following:
private void SerializeData()
{
XmlSerializer ser = new XmlSerializer(typeof(ObservableCollection<MyTask>));
Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
using (var writer = new StreamWriter(File.Open(Path.Combine(installedLocation.Path,sFileName), FileMode.OpenOrCreate)))
{
try
{
ser.Serialize(writer, sData);
}
catch (Exception ex) { }
}
}
This is MyTask model:
public class MyTask:ViewModelBase
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
}
The error that I've been getting is UnauthorizedAccessException. I remember that when I was creating my regular Windows 7 apps under WPF, I had no problem with permission. This is my first UWP app, and therefore I might have forgotten to do something with permissions.
The questions is - is it possible to store simple file in installed directory, or do I need to store all my data files under some Shared location?
Package.InstalledLocation is a place where your app is installed and it's read-only - so you cannot write files there. Use ApplicationData.LocalFolder instead - this is the folder where your app should store local data. For more info how to store (and where), please take a look at MSDN.
Apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities.
The locations that all apps can access
When you create a new app, you can access the following file system locations by default:
Application install directory. The folder where your app is installed on the user’s system.
There are two primary ways to access files and folders in your app’s install directory:
You can retrieve a StorageFolder that represents your app's install directory, like this:
Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
You can retrieve a file directly from your app's install directory by using an app URI, like this:
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///file.txt");
The app's install directory is a read-only location. You can’t gain access to the install directory through the file picker.
Application data locations. The folders where your app can store data. These folders (local, roaming and temporary) are created when your app is installed.
There are two primary ways to access files and folders from your app’s data locations:
Use ApplicationData properties to retrieve an app data folder.
For example, you can use ApplicationData.LocalFolder to retrieve a StorageFolder that represents your app's local folder like this:
using Windows.Storage;
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
you can retrieve a file directly from your app's local folder by using an app URI, like this:
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt");
User’s Downloads folder:
using Windows.Storage;
StorageFile newFile = await DownloadsFolder.CreateFileAsync("file.txt");
and much much more ... for further reference goto dev.windows.com and you will get a ton of resources.

Categories