[UWP][C#]Delete a File on C: drive using C# UWP RRS feed

  • Question

  • I'm writing a simple app that deletes a cache file that causes problems with another program, and the solution is to delete the cache file which will be re-written when the app is opened. Instead if having people dig through the file system I want to make this a simple one click process.

    My problems is File.Delete() does not work with the UWP app. I keep getting an error in VS2015 that says:

    "An exception of type 'System.InvalidOperationException' occurred in System.IO.FileSystem.dll but was not handled in user code
    Additional information: Synchronous operations should not be performed on the UI thread.  Consider wrapping this method in Task.Run."

    This code works fine in a WPF app, I have looked everywhere to find the solution for a UWP app but came up empty, so hence, this post.

    It's an extremely simple app. All I need is to click a button and have the file deleted. I can do the XAML design, add in progress bars ect... later, I just need this code to work and haven't been able to find the correct answer.

    Any suggestions on how to write this for a UWP app using C#...

    public sealed partial class MainPage : Page
            public MainPage()
            private void button_Click(object sender, RoutedEventArgs e)
              File.Delete(@"C: \Users\username\Documents\TESTME1.txt");

    Obviously that's a dummy file path which I'll change once the process works. I tried wrapping in an if/else but that didn't work either. I'm sure the answer is simple, thanks for any insights, I'm very new to UWP.

    Saturday, August 20, 2016 1:00 AM


  • Since your goal is to affect an arbitrary file on the system you're probably better off with a WPF app than a UWP app.

    UWP apps are specifically limited in their ability to affect the system as a whole. They have direct access only to their own files.

    The problem you're running into is that your app doesn't have access to the path you're using and so can't see the file to delete it. If you used a path within the app's app data directory then what you have should work.

    To access files elsewhere you'll need to get a StorageFile for it. For arbitrary locations you'll need to have the user pick them with the FilePicker. For library folders you can declare capabilities to create StorageFiles.

    See File access permissions , Files and folders in the Music, Pictures, and Videos libraries , and Files, folders, and libraries

    • Proposed as answer by Azat Tazayan Saturday, August 20, 2016 8:20 AM
    • Marked as answer by Barry Wang Wednesday, August 31, 2016 7:15 AM
    Saturday, August 20, 2016 2:01 AM