UWP C# File.WriteAllLines

VoyTec 671 Reputation points
2021-06-20T23:10:16.29+00:00

Hello,

I am using following code:

   string path = @"c:\temp\MyTest.txt";
   string[] createText = { "Hello", "And", "Welcome" };
   File.WriteAllLines(path, createText, Encoding.UTF8);

and it crashes my app witha an unsupported exception error.
What should I do?

Developer technologies Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-06-21T07:16:19.227+00:00

    Hello,

    Welcome to Microsoft Q&A!

    I tested your code. The app crashed with a UnauthorizedAccessException: 'Access to the path 'c:\temp\MyTest.txt' is denied.'. This behavior is expected. I'll explain it next.

    UWP apps are different from desktop applications when accessing the file system. UWP apps are running in the sandbox so there are limitations for UWP apps when trying to access the file system. You could check this document: File access permissions. The document lists all the locations that UWP apps have permission to access.

    Back to your scenario, you are trying to access a file listed in C:. This is a location that UWP doesn't have permission to access by default. First, you need to add the broadFileSystemAccess restricted capability. This capability enables your app could use the StorageFile.GetFileFromPathAsync() API with a Path parameter. This is mentioned in the last part of the document I posted above. Then please go to Settings > Privacy > File system, enable your app in the list. Like this:

    107513-image.png

    After you've added the broadFileSystemAccess restricted capability and enabled your app in the settings, now you could change your code like this:

                string[] createText = { "Hello", "And", "Welcome" };  
                StorageFile file = await StorageFile.GetFileFromPathAsync(@"c:\temp\MyTest.txt");  
                await Windows.Storage.FileIO.WriteLinesAsync(file, createText, Windows.Storage.Streams.UnicodeEncoding.Utf8);  
    

    This should work correctly as you wanted.

    Thank you.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.