简体   繁体   中英

UnauthorizedAccessException was unhandled

I'm trying to take input and convert that to a .csv file then create a directory for the folder and save that file within the directory. Once I run my code, I'm able to create the directory and file. However, this is supposed to happen after I click the button and does so before. The exception is thrown right after I click the button. I'm using WPF and coding in C#. What would cause this exception?

Here is a snippet

private void updateBANKEevent(object sender, RoutedEventArgs e)
    {

        //Convert input to CSV format
        string userInput = tellerID.Text + "," + vaultSerial.Text + "," + QR.Text;
        var bnkDir = @"C:\Program Files\Bank_Data";


        //generate headers for CSV file
        if (!Directory.Exists(bnkDir))
        {
            string bnkHeader = "tellerID" + "," + "Vault Serial Number" + "," + "QR Code" + Environment.NewLine;
            Directory.CreateDirectory(bnkDir); <--Exception is thrown here
            File.WriteAllText(System.IO.Path.Combine(bnkDir,"Bank_Data.csv"), bnkHeader + userInput);

        }

        // Append new input to existing file
        File.AppendAllText(System.IO.Path.Combine(bnkDir),userInput + Environment.NewLine);
        }

The exception is quite clear. The user is not authorised to create the specified directory.

Given that the folder is "C:\\Program Files\\Bank_Data" it will be the case that a regular user won't have the rights to create files or directories whereas an admin user (which you probably are) will.

You need to choose a folder that all users have rights to to store your data, which by default will be %APPDATA%\\<your app> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM