I wanted to create some simple practice code in UWP that opens up a text file, then immediately appends that code with trivial text.
public MainPage()
{
this.InitializeComponent();
OpenFile();
SaveFile();
}
public async void OpenFile()
{
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.Desktop;
picker.FileTypeFilter.Add(".txt");
DataFile = await picker.PickSingleFileAsync();
if (DataFile == null) { return; }
}
public async void SaveFile()
{
await FileIO.AppendTextAsync(DataFile, "" + DateTime.Now + "\n");
}
private StorageFile DataFile { get; set; }
As expected, this code returns an error since in SaveFile() method, since SaveFile() runs immediately after OpenFile() and since OpenFile() has not completed its operation of retrieving the target file for SaveFile() to use. The thing is, when I try to modify the following code in OpenFile, I receive an AggregateException error:
DataFile = picker.PickSingleFileAsync();
Task task = Task.Run( async() => DataFile = await picker.PickSingleFileAsync() );
task.Wait();
I was wondering how I can block OpenFile() until it is done retrieving the target file, before SaveFile() runs.