Reputation: 654
I'm trying to create a file then write to the file and read from it as well... kind of like settings for my app to load every time it loads. Why is this not working for me? I'm running visual studio 2012 and I think when I run the program there the file should be created in the project's folder... my method it's async and void... don't really know what is going on haha
StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("config.txt", CreationCollisionOption.ReplaceExisting);
How can I create this in the local folder? so every time the program runs no matter in what computer it will create the file and load it when the user close and re-open the program?
Upvotes: 1
Views: 1369
Reputation: 31803
Man, great question!
Here's the exact logic to do what you are asking:
public class MyData
{
public string Title { get; set; }
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = await LoadData();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SaveData(this.DataContext as MyData);
base.OnNavigatedFrom(e);
}
private async Task<MyData> LoadData()
{
var _Data = await StorageHelper.ReadFileAsync<MyData>(
this.GetType().ToString(), StorageHelper.StorageStrategies.Local);
return _Data ?? new MyData() { Title = "Welcome" };
}
private async void SaveData(MyData data)
{
await StorageHelper.WriteFileAsync(
this.GetType().ToString(), data, StorageHelper.StorageStrategies.Local);
}
}
The StorageHelper class can be found here. or on my blog http://jerrynixon.com
Best of luck!
Upvotes: 1
Reputation: 292365
How can I create this in the local folder?
You can't, and anyway you're not supposed to... Windows Store apps run in a sandbox, they have a very restricted access to the file system. Basically, you have access to:
LocalFolder
(which is not the installation folder) and RoamingFolder
And I think that's about it... You can also access the files in the installation folder (Package.Current.InstallationFolder
), but only for reading.
Upvotes: 0