1

I know that there are a lot of questions concerning getting a

"System.UnauthorizedAccessException".

However I couldn't find a solution in any of these questions, as most of the answers refer to one of these Microsoft help pages.

My Situation: I try to save some user input as .csv, so I can import it when needed.

My Code:

var csv = new System.Text.StringBuilder();
            string dir = Path.Combine(Environment.GetFolderPath
            (Environment.SpecialFolder.DesktopDirectory), "test.csv");

            var newLine = string.Format("{0},{1},{2},{3},{4}", txtFirstName.Text, txtLastName.Text, txtEmail.Text,
                txtPhone.Text, txtPlace.Text);

            csv.AppendLine(newLine);

            if (!File.Exists(dir))
            {

                using (FileStream fs = File.Create(dir))
                {
                    Byte[] info = new System.Text.UTF8Encoding(true).GetBytes("FirstName,LastName,Email,Phone,Place");
                    // Add headers to the file.
                    fs.Write(info, 0, info.Length);
                }
            }

            try
            {
                File.AppendAllText(dir, csv.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }

As you can see, I'm trying to write everything to my Desktop, in a file called "test.csv". I am running Visual Studio as an Administrator and the file I have on my Desktop is not read-only. Does anybodoy have an idea why this still fails?

Edit: I'm running this as a Standard UWP-App on a desktop Computer.

Tobias Nöthlich
  • 181
  • 1
  • 12
  • what is the application where you execute this code, a console application, a web application...? – animalito maquina Mar 09 '18 at 09:18
  • Oh yes, sorry I forgot to clarify. The application is a Standard UWP-App, running on a Desktop Computer. – Tobias Nöthlich Mar 09 '18 at 09:20
  • 1
    Have you check the user that runs the app from the task manager? And when you get the exception, at File.Exists, at File.Create, at File.Append? – animalito maquina Mar 09 '18 at 09:21
  • I miss a `fs.Close()` here.. – Essigwurst Mar 09 '18 at 09:22
  • Sure, it is run by "Administrator". – Tobias Nöthlich Mar 09 '18 at 09:23
  • @Essigwurst Indeed, but it already throws the exception on "File.Create". – Tobias Nöthlich Mar 09 '18 at 09:24
  • Possible duplicate of [Access C Drive files in UWP AppService](https://stackoverflow.com/questions/39873024/access-c-drive-files-in-uwp-appservice) – Diado Mar 09 '18 at 09:25
  • What happens when you use `File.WriteAllBytes()` instead of `FileStream` ? – Essigwurst Mar 09 '18 at 09:25
  • @Essigwurst Still throws the exception. This time at `File.WriteAllBytes()` – Tobias Nöthlich Mar 09 '18 at 09:27
  • 1
    UWP is very strict about creating and accessing files. I'd suggest having a look at the [File Access Permissions documentation](https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions), and then the [Create, Write and Read Quickstart](https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files), and using the `Windows.Storage` namespace for file operations. – Diado Mar 09 '18 at 09:37
  • 1
    Since this is UWP app did you add broadFileSystemAccess in the manifest? – Ken Tucker Mar 09 '18 at 09:38
  • 4
    you should also focus on naming in you code. It's pretty unclear to name a **file** `dir` ... – Felix D. Mar 09 '18 at 09:39
  • I can't recreate the exception running your code in a console application, so the code is fine. I think you are experiencing a permission issue. you can read this https://stackoverflow.com/questions/15974590/system-unauthorizedaccessexception-while-creating-a-file – demo.b Mar 09 '18 at 09:45
  • @Diado Using the `Windows.Storage` Namespace lets me create a file, however this file is hidden somewhere deep in AppData Folder. Is there a way to save it to "Documents" or the like? – Tobias Nöthlich Mar 09 '18 at 09:46
  • @demo.b I actually read this question already. The answer for him was to point to a file not a directory. – Tobias Nöthlich Mar 09 '18 at 09:48
  • @Felix.D You're right. Before asking the question I made the mistake to point to a directory and forgot to rename the variable. – Tobias Nöthlich Mar 09 '18 at 09:49
  • 1
    There are a number of ways to access various file system locations in UWP, using `StorageFolders` - If it's a known folder, look at the [KnownFolders class](https://learn.microsoft.com/en-us/uwp/api/Windows.Storage.KnownFolders#Windows_Storage_KnownFolders_DocumentsLibrary). If you want wider access you need to add `BroadFileSystemAccess` to the manifest, as @KenTucker suggested. – Diado Mar 09 '18 at 09:54
  • @Diado Thanks a lot, with your help I managed to save my files to the documents Folder. Do you want to formulate an answer or shall I describe what i did for people looking here in the future? – Tobias Nöthlich Mar 09 '18 at 10:29
  • I only provided links for background reading - glad they helped :-) Feel free to add an answer yourself if you like, I probably won't have time until this afternoon (someone thought Friday was a good day to do a live release :-/ ) – Diado Mar 09 '18 at 10:34
  • Is it ok if the user has to explicitly browse to a specific folder where they want to save the file once and you can read/write to the folder always after that ? – Pratyay Mar 09 '18 at 10:38
  • 1
    @Praytay Yes, but I aready solved the problem. Saving and reading .csv-files from the documents folder now works, which is all I needed. – Tobias Nöthlich Mar 09 '18 at 10:39
  • ok .. happy coding ..! – Pratyay Mar 09 '18 at 11:07

1 Answers1

2

From a UWP process file access is restricted. In order to write to the desktop (or any arbitrary location) your app will need to use the file save dialog and let the user confirm/choose the location. Then you will be able to save to the desktop or whatever location the user has decided to select.

In the upcoming Spring 2018 update for Windows 10 we will introduce a new capability ('broadFileSystemAccess') for UWP applications that will make this better. If you declare this capability in your manifest, the app will ask for user consent on first launch for broad file system access, and then you will be able to access all locations that the current user has access to.

If you need a solution that works on earlier versions of Windows 10 (prior to Spring 2018 update) and the file dialog is not a viable option then you can look into adding a fulltrust process to your UWP package that handles the file operations on behalf of your UWP process. You can launch that fulltrust process from the UWP via the FullTrustProcessLauncher API: https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.fulltrustprocesslauncher

Stefan Wick MSFT
  • 13,600
  • 1
  • 32
  • 51
  • Btw, regarding the "running as admin" part of your question: Even though you run VS as admin, the launched UWP process still runs unelevated. UWP apps can not be run with elevated privileges. – Stefan Wick MSFT Mar 09 '18 at 20:25