I am following steps provided in This link. But i am getting "System.UnauthorizedAccessException" while reading file (text File"); . I tried following solution also but not succeed.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///ewr.txt", UriKind.RelativeOrAbsolute));
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
please tell me hoe to solve it.
Try running the code with administrator rights. Your application is trying to access a location which is by default restricted. Another alternative is to store the file in a place where the logged in user has access i.e. application data folder of user.
Problem is not with your code but the effective access rights of the file. However, you can resolve it with changes in code.
Related
I use the types StorageFile, StorageFolder and they need access to the file system, since the file is not opened by the user:
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(filePath);
I need so that I can give the user permission to access the file system to my application:
How can I do it?
Your screenshot is app's access permission setting page, after add broadFileSystemAccess capability, your app will display in the list, you also need to manually enable broad file system in File System setting page. For getting the setting page, you could search file system keywords in setting app home page.
If you want to quickly access this page, you could use the following method. For more info please refer Launch the Windows Settings app.
bool result = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-broadfilesystemaccess"));
For more info please refer uwp File access permissions.
i need to synchronous write on a file, i know that there are methods to do that async but thats not my case.
after navigate from an other page.xml i come to my main page and in the onnavigated method i need to write in a file.txt a text that i takes from the previous page.
(that's how i thought to save a data from a first open of the app and every time the app will open it will load these data to not make tutorial anymore)
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Regione = e.Parameter as regione;
string ciccio = "" + Regione2.RegNome.ToString() + "," + Regione2.RegLat.ToString() + "," + Regione2.regLon.ToString();
//File.WriteAllText("Data/data1.txt", ciccio);
File.WriteAllText("C:/Users/giuli/Documents/Source/xxx/XXX/XXX/Data/data1.txt", ciccio);
}
and if i try with the File.WriteAllText("C:/Users/giuli/Documents/Source/xxx/XXX/XXX/Data/data1.txt", ciccio);
i get an exception that tell me that i cannot use sync method:
"Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run."
ok but i need to, and i tried with File.WriteAllText("Data/data1.txt", ciccio);
and i get an
System.UnauthorizedAccessException:
access to the path denied
and if i try with some async method
Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile File2 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/data1.txt"));
await Windows.Storage.FileIO.WriteTextAsync(File2, ciccio1);
i get an
System.UnauthorizedAccessException: 'Accesso negato
i created the file data.txt via visual studio, it's not open on VS and i think noone know that that file exist rather than VS.
How can i finally write on that file ?
Thanks .)
"the read sync and async method work perfect so it's not a problem about the path
Regione.RegNome = File.ReadAllText("Data/data1.txt");"
Other than the error saying not to call synchronous API from the UI thread none of the other errors you have are related to the API being synchronous or asynchronous. They all look like legitimate errors because the app doesn't have access to write to the locations it attempts to write to.
Use ApplicationData.RoamingSettings to store your seen-the-tutorial flag. You don't need to manage this yourself in a file. See Store and retrieve app settings and data for details.
The UnauthorizedAccessException on ms-appx:///Data/data1.txt is because an app's install location is read only. Sync vs. async isn't relevant here: reading but not writing from this location is expected to work. The install location is also shared between users, so even if the app could write here it wouldn't be a good place for user-specific data like a seen-the-tutorial flag. If you want to store this in a writable user-specific file then use ApplicationData.LocalFolder or RoamingFolder as described in Store and retrieve app settings and data
The app doesn't have direct access to the Documents folder. With appropriate capabilities it can get brokered access to that folder via the StorageFile class, but the app won't have direct access using System.IO.File.
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.
I am creating an app that is tracking GPS data (latitude, longitude, altitude). So far I've managed to create a listbox that gets an extra line everytime another set of coordinates is made.
I tried writing it to file with this function.
private async Task WriteToFile()
{
string ResultString = string.Join("\n", locationData.ToArray());
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(ResultString);
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var file = await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
I can read this file, but I can't view this "DataFile.txt" anywhere in Files app.
I tried using WP Power Tools, but it doesn't work with 8.1, I am unable to update Visual Studio 2013 in order to get ISExplorer.exe working and
IsoStoreSpy keeps crashing everytime I try to connect my Lumia 620.
But all of this looks too complitated to me. Is there any other way of getting this .txt file without messing with IsolatedStorage? I feel like I'm missing out on something so simple here, I just can't believe that such basic thing as writing output to .txt, that can be later used by PC, couldn't be available.
You're storing the file in your app's local storage (Windows.Storage.ApplicationData.Current.LocalFolder), which is the same as Isolated Storage.
The Files app can see only public locations not app-specific locations.
There are several ways your app can share this file more globally:
Use the share contract to let the user share the file to wherever they'd like (OneNote, Email, etc.). See Sharing and exchanging data
Let the user choose where to save the file with a FileSavePicker. See How to save files through file pickers
Save the file on the SD card. See Access the SD card in Windows Phone apps.
Save the file to the user's OneDrive. See Guidelines for accessing OneDrive from an app
Save to a RoamingFolder so the file can be read by the same app on a Windows PC, which can then export using similar methods (especially a file picker) but on the desktop device. See Quickstart: Roaming app data
I am trying to read the chrome bookmark file within a windows 8 app. Problem is I am getting the 'System.UnauthorizedAccessException' exception. So basically you have to register a file type association in the app manifest but the file has no extension.
File: C:\Users\<User>\AppData\Local\Google\Chrome\User Data\Default\Bookmarks
Is this even possible in windows 8 apps?
UPDATE
Here is my file access code:
public async Task<string> ReadFile(string filename)
{
if (await FileExists(filename))
{
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filename);
var stream = await file.OpenReadAsync();
var reader = new StreamReader(stream.AsStream());
return await reader.ReadToEndAsync();
}
else return string.Empty;
}
Windows 8 app cannot access any random file system location. It can only access
Application Folder (which is specific to your app)
Common Folders like My Pictures, My Video and similar
See this article for complete details
A workaround is to use the file picker. This allows the end user to manually select files on the filesystem. Once you have the FileStorage object from the file picker, you can then open and read the file.
Optionally, you can then save the StorageFile for later use, meaning that your app can access the file later, without the end user having to select the file again.
More info on MSDN:
File Open Picker
How to track recently used files and folders