1

I can't seem to change the read only flag on a file. I've tried this on Vista and XP with the same result, so I don't think it's a UAC related issue.

Nothing I've done seems to work though. See the sample below. Can someone tell me what I'm doing wrong?

public bool UpdateResFile(string fileName, string language, string objectName, string NewValue)
{
    FileInfo fi = new FileInfo(fileName); 
    try
    {
        //Do Stuff                
        xDoc.Save(fileToUpdate);
    }
    catch (UnauthorizedAccessException)
    {
        //fi.IsReadOnly = false;
        File.SetAttributes(fileName, FileAttributes.Normal);
        //fi.Attributes -= FileAttributes.ReadOnly;
        return UpdateResFile(fileName, language, objectName, NewValue);
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
    return true;
}

2 Answers 2

2

Is not possible to change the read only attribute of a file at UnauthorizedAccessException cause the application is executing with the permissions that you have in the computer.

If you dont have permissions to change normally this file to read only, your application will not change this attribute either.

Kind Regards. Josema.

Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to change read-only flag on file WHEN you get an UnauthorisedAccessException. You can't do that. All you can (and should) do is to notify user that he/she has no access rights to save file there, and offer to save somewhere else.

1 Comment

That did it!! I moved the check higher up and it worked great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.