Read text files with windows store apps - c#

I am working with Visual Studio ultimate 2013 and using windows store apps.
My visual studio project folder "History"(name of the current project) is located in D:Academic folder.
I have created text file in the History project folder.
And I want to print the details in text file to a text block.
This code works.
According to this, the location of the text file is created in Local Folder.
public History()
{
this.InitializeComponent();
StorageFolder = ApplicationData.Current.LocalFolder;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
ReadText();
}
async void ReadText()
{
StorageFile file = await StorageFolder.GetFileAsync(filename);
ghij.Text = await FileIO.ReadTextAsync(file)
}
private void Write_click(object sender, RoutedEventArgs e)
{
WriteText();
cdef.Text = "";
}
async void WriteText()
{
StorageFile file = await StorageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, cdef.Text);
}
In my case I don't want to create and write a file,but to READ an already created file which is located in D:\Academic:\History folder.
So how can I change the path to access the text file.
Please help.

Windows store apps don't have full access to the file system. You can give them access however to specific places like the Documents through the so called capabilities. You can also save and restore content from local storage.

You don't have direct access in Windows Store Apps. FilePicker class would serve you most of the time to open a file but if you want a programmatic access to a file then you need to declare appropriate capabilities in your package manifest.
And yes you want to access documents library, in that case you have to declare documents library capability in your package manifest.
From MSDN :
The file picker provides a robust UI mechanism that enables users to open files for use with an app. Declare the documentsLibrary capability only when you cannot use the file picker.
NOTE : Documents library only gives access to file formats filtered by the types declared in the manifest.
For eg. For example, if a DOC reader app declared a .doc file type association, it can open .doc files in Documents, but not other types of files.
You can't use the Documents library in a Windows Phone Store app.
You can't publish a Windows Phone Store app that specifies the documentsLibrary capability to the Windows Phone Store. The Store blocks the publishing of the app.
You can refer MSDN Arcticle on Manifest capabilties.

Related

PCLStorage FileSystem is only available in Android, not iOS

I'm writing a cross platform application in xamarin, for Android and iOS, and I need to save some text files to local storage. I'm using PCLstorage, but whenever I mouse over any PCLStorage code, it says "MyApplication.Android: available, MyApplication.iOS not available". How can I use PCLStorage to store files on both platforms? Or is there another way I can do this? Here's an example of some of my code:
public async Task CreateRealFileAsync(string filename, string filebody)
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("DadAppFiles", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync(filebody);
}

Is it possible to save a file to an exact, specific location? (Windows 8.1 Universal App C#)

What I need to do:
Save an image file to an exact, specific location when the app is run (Let's say "Z:\test\photo.jpeg").
Additional wanted functionality:
1) Overwrite the file ''Z:\test\photo.jpeg' if it already exists.
2) Skip the write, if the folder 'Z:\test\' doesn't exist.
What I've already tried:
using Windows.Media.Capture.UI;
using Windows.Storage;
CameraCaptureUI camera = new CameraCaptureUI();
StorageFile photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("photo.jpeg", CreationCollisionOption.ReplaceExisting);
if (targetFile != null)
{
await targetFile.DeleteAsync();
await photo.MoveAndReplaceAsync(targetFile);
}
}
Question:
Is there a way to get the variable 'targetFile' to point to a particular location, eg. "Z:\test\photo.jpeg"?
I don't want to use local app data folder, pictures folder, or anything like that. It needs to be this particular location.
Univeral Apps are sandboxed and can only access their on storage folders.
You can grant access to other files using FileOpenPicker or FolderPicker, but you won't have control about what file the user picks for you to write into.
This means you have to make your user pick that exact file for you to store at, otherwise your app can't access that location.
Here's an overview on accessible file locations for UWP apps on MSDN.

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.

WP8.1: Exporting data to "reachable" .txt file

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

'System.UnauthorizedAccessException' on reading file no extension

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

Categories