In my UWP app, to get the path of the user's downloads folder, I am importing Shell32.dlland invoking the method SHGetKnownFolderPath with the shell folder value for downloads folder "{374DE290-123F-4565-9164-39C4925E467B}" (as mentioned in Windows 10 User Shell Folders Restore Default Paths).
Now my question is, does the above way of getting the folder path, violate any UWP recommendation? Will my app pass the certification for publishing in Microsoft store? Or will it be rejected as mentioned in the answer to this question - How to access registry key in a UWP app?
A more general answer: You can use the UserDataPaths class as a replacement for SHGetKnownFolderPath in Windows 10.
For using download folder in uwp, you could use Windows.Storage Api. If you want to create file in download folder you could use the follow.
StorageFile sf = await DownloadsFolder.CreateFileAsync("testMarker");
And you could get the path of DownloadsFolder via the above file. But you could not access the file with path directly.
StorageFile sf = await DownloadsFolder.CreateFileAsync("testMarker");
ArrayList numbers = new ArrayList(sf.Path.Split(new char[] { '\\' }));
numbers.RemoveRange(numbers.Count - 2, 2);
var downloadPath = string.Join("\\", numbers.ToArray());
SHGetKnownFolderPath is not support in uwp, But you could use it in an desktop-bridge app you could call any methods before you convert your desktop app to UWP app.
Related
I'm working on my first WinRT app and I do not seem to be able to find any code that would allow me to loop through a directory and get file names that are in that directory?
I have found plenty of code to do it in a normal winform, wpf and console but nothing really for the Winrt variety.
The closest I've come to code:
Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");
But that just seems to get files that are withinn my own project?
How would I go about scanning a normal directory like "c:\something\something"?
I'm working on my first WinRT app and I do not seem to be able to find any code that would allow me to loop through a directory and get file names that are in that directory?
If you want to loop through a directory within UWP, you could use GetFilesAsync to get a file list from a directory.
However, UWP run sandboxed and have very limited access to the file system. For the most part, they can directly access only their install folder and their application data folder. Access to other locations is available only through a broker process.
You could access #"c:\something\something"via FileOpenPicker or FolderPicker.
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
}
else
{
}
And this is official tutorial you could refer to.
I am attempting to create a directory using this method that fires after a button press in app, as well as add a file to it:
DirectoryInfo d = new DirectoryInfo(#"..\\newFolder\\");
FileInfo f = new FileInfo(#"..\\newFolder\\foo.txt");
if (!d.Exists)
{
d.Create();
}
if (!f.Exists)
{
f.Create().Dispose();
}
Here's the error that is producded in my Universal App as a result of doing this:
An exception of type 'System.UnauthorizedAccessException'
occurred in System.IO.FileSystem.dll but was not handled in user code
Additional information: Access to the path
'C:\Users\[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder' is denied.
Any one familiar with this error or know of any suggestions?
EDIT
In addition to the below, this is a Great resource for working with file systems in the Windows 10 Universal App environment: File access and permissions (Windows Runtime apps) https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh758325.aspx
The problem is that you are trying to create a file inside your app's install folder, and that is not allowed for Universal Apps. You can only create folders inside your local data folder.
Try this:
using Windows.Storage;
var localRoot = ApplicationData.Current.LocalFolder.Path;
DirectoryInfo d = new DirectoryInfo(localRoot + "\\test");
if (!d.Exists)
d.Create();
Try This
public static async void WriteTrace()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
}
Every application runs under (by) a specific user and inherit it's privileges, authorities, limitations and ...
so
The User that your app runs under it, haven't enough privilege and can't create a folder
SO you can:
Use Impersonation (search impersonation c#) and code your app to runs as another User with required privilege (Like Administrator). after that your application always runs as administrator (or specific user) automatically. (If you impersonation your app as Administrator, Be aware of Security issues)
Run your application as Administrator (or a user with enough privilege) manually. (for Administrator right click on your-app.exe and click on "Run as ...")
Change security settings and access limits for your working directories (e.g C:\Users[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder ) and give write access to your username
Run your application with Administrative privileges and it should be done.
I have tried to launch a file from the computer in many ways, suppose is d:\a.pdf
1.- Tried with Launcher.LaunchFileAsync but needs StorageFile that should be GetFileFromPathAsync but as everybody knows W10 apps are unauthorized to open such that path.
2.- Tried using file:/// like file:///d:/a.pdf but it simply returns false
var success = await Launcher.LaunchUriAsync(new Uri("file:///d:/a.pdf", UriKind.Absolute), options);
3.- Launcher.FindFileHandlersAsync() neither returns empty.
So is there any way to launch files?
There is no way to launch files from paths that the app doesn't have permissions to read. Apps don't have access to d:\
You can use LaunchUriAsync to launch files by path from within the app package or app data directories, but not elsewhere. Using the ms-appx: or ms-appdata: protocols is a cleaner way to address those locations.
If you have permission then you can get a StorageFile. This will allow launching files from libraries, locations chosen via FilePicker, files clicked on to launch the app (though that would be circular), etc.
I use the "Sqlite for Windows Runtime" and sqlite-net (just as described at http://timheuer.com/blog/archive/2012/08/07/updated-how-to-using-sqlite-from-windows-store-apps.aspx) to develop a Windows 8 Metro-App, just . If I want to open a Database at the Program-Directory is no problem:
var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
using (var db = new SQLite.SQLiteConnection(dbPath)) {
...
}
But when I want to use an extern Path like this:
var dbPath = "C:\\Users\\xxxxxx\\db.sqlite";
then an error occurs with "Cannot open database file". Why? Here I am using C#, normally I use C++, but for this problem I am sure it doesn't matter ;)
You cannot select arbitrary files on the file system. See here for details.
By default you can access these locations:
Application install directory
Application data locations
User’s Downloads folder
and
Additionally, your app can access some of the files on connected
devices by default. This is an option if your app uses the AutoPlay Device extension to launch automatically when users connect a device,
like a camera or USB thumb drive, to their system. The files your app
can access are limited to specific file types that are specified via
File Type Association declarations in your app manifest. Of course,
you can also gain access to files and folders on a removable device by
calling the file picker (using FileOpenPicker and FolderPicker) and
letting the user pick files and folders for your app to access. Learn
how to use the file picker in Quickstart: Accessing files with file pickers.
If you have the right capabilities declared you can also access:
Documents Library
Music Library
Picture Library
Videos Library
Homegroup Library
Removable devices
Media server devices (DLNA)
Universal Naming Convention (UNC) folders
A combination of the following capabilities is needed.
The home and work networks capability:
PrivateNetworkClientServer
And at least one internet and public networks capability:
InternetClient InternetClientServer
And, if applicable, the domain credentials capability:
EnterpriseAuthentication
Note You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.
In windows metro application...
It support only sandbox property of an application.
So you cant use
var dbPath = "C:\\Users\\xxxxxx\\db.sqlite";
U can only store data in local storage or application installed directory.
Please avoid to use any other path . it will not work .
I have a doubt from a silverlight application we can access MyDocuments. I am creating an Application which will download a set of files from a remote server . Is it possible to save these file in MyDocuments instead of Isolated Storage. I am using Silverlight 4.0 . Can any one give me Sample codes for it.
In order to acheive that you need to use Silverlight 4 and specify that is should get elevated privileges when install as an Out-of-browser application. When running as an OOB the app will have access to the users Documents folder.
In all other cases you will need to use the SaveFileDialog where the user can explictly specify where to save the file.
Edit code example:-
if (Application.Current.HasElevatedPermissions)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Combine.Path(path, "MySaveFile.dat");
using (var filestream = File.OpenWrite(path))
{
// pump your input stream in to the filestream using standard Stream methods
}
}
No Isolated storage is currently the only option.