I have been trying to write a C# application on Win10 that only runs a background task that writes into a file.
Running the code below throws UnauthorizeAccessException exception after the trigger, 'Access to the path 'C:\temp' is denied'. The file and directory both have full access for Everyone.
Also, what can background tasks access/run? I am trying to run a background task while in modern standby and for it to read some registers and/or run another tool. Is that even possible while still in modern standby?
Here is the code of my attempt in doing so:
Background task:
using Windows.ApplicationModel.Background;
using System.IO;
namespace RuntimeComponent2
{
public sealed class Class1 : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
File.WriteAllText(@"C:\temp\test.txt", "test");
}
}
}
Main page:
using System;
using Windows.ApplicationModel.Background;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace App3
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var exampleTaskName = "MyTask1";
foreach (var t in BackgroundTaskRegistration.AllTasks)
{
t.Value.Unregister(true);
}
await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "RuntimeComponent2.Class1";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
BackgroundTaskRegistration task = builder.Register();
}
}
}
You cannot do that, and the problem is not regarding the BackgroundTask. Inside a UWP application you cannot write on your hard-disk. The only places you can read & write is accessible using ApplicationData.Current (LocalCacheFolder, LocalFolder and so on), or any folder the user choose explicitly using SaveFilePicker.
Furthermore, you need to use this syntax (Intellisense suggests you to use the class File, but in UWP isn't really available)
FileIO.ReadTextAsync(StorageFile file);