Home > Software engineering >  System.UnauthorizedAccessException, trying to use XML serialization
System.UnauthorizedAccessException, trying to use XML serialization

Time:10-21

This is the function I use to save the data. The data is stored inside holder(SettingsHolder). The directory I need is recognised but it does not have permission.

        //Save the data of a new user, called by NewUser();
        public static void SaveNew(string filename)
        {
            UserLogins.SettingsHolder holder = new UserLogins.SettingsHolder();

            FileStream stream = new FileStream(filename, FileMode.Create);
            var XML = new XmlSerializer(typeof(UserLogins.SettingsHolder));
            XML.Serialize(stream, holder);
        }

This is where I call SaveNew:

        public static void NewUser()
        {
            UserSlot = FindLastEmptyUser();

            // Set user default settings.
            Console.WriteLine(users[UserSlot]);
            Console.WriteLine("What will the new user's name be?");
            UserLogins.SettingsHolder.name = Console.ReadLine();
            users[UserSlot] = UserLogins.SettingsHolder.name;

            UserLogins.SettingsHolder.status = 0;
            Console.WriteLine("Ok, I made a new user called "   users[UserSlot]);
            Console.WriteLine("");

            // Write defaults to XML file

            SaveNew(Environment.CurrentDirectory   users[UserSlot]);
            UserDataLoader.PromptUsers();
        }

I have tried the instructions of other people who have asked this question but they didn't work.

The exact error message is System.UnauthorizedAccessException: 'Access to the path 'C:\Users\(my user)\OneDrive\Desktop\Projects\dotnet\dotnet1\bin

Can anyone help me here?

CodePudding user response:

Fixed it, the file was in the Users(my user) directory so it did not have access, only the user and admins have access to that. I moved it to C:\ and it fixed itself.

I had the problem again on a different project so just in case that didn't work for other people, I had set filename to a directory, make sure it includes the name of the file as well as the directory

  • Related