UnauthorizedAccessException (581991)

I’m getting UnauthorizedAccessException (Access to path is denied) every time I try to read file that my program has written. I tried every advice I’ve found: made sure paths are correct, tried persistentDataPath, tried localDataPath tried custom directories, tried to run as administrator, tried to disable all antivirus and firewall programms.. Still getting this exception.

Here is my code:

private void SerializeObject <T> (T obj, string path, string fileName)
    {
        BinaryFormatter bf = new BinaryFormatter();
        System.IO.Directory.CreateDirectory(path);
        FileStream file = File.Open(path + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        bf.Serialize(file, obj);
        file.Close();
    }

    private T DeserializeObject <T> (string path, string fileName)
    {
        T obj = default(T);
        if (System.IO.Directory.Exists(path))
        {
            //File.SetAttributes(path, FileAttributes.Normal);
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            print("opened");
            obj = (T)bf.Deserialize(file);
            print("deserialized");
            file.Close();
        }
        return obj;
    }

Please help me find solution. And I repeat that only deserialization throws exception. Nothing else is printed in console. Paths are correct, and data types are correct.

I know it’s a little late, but you’re creating a path you don’t have access to.

refer to this as an example. here i’m writing to the desktop.

string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string fullFileName = Path.Combine(desktopFolder, "Test.txt");
string fs = new FileStream(fullFileName, FileMode.Create);

hope this helps.

Oh, thank you. How silly of me… I forgot to add:

FileStream file = File.Open(path + fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

instead of just path, I see. Deserialize() method used to take just one variable for a full path and after I split it, I forgot to change that line. And the answer is actually just in time)