0
Answer

Can't run more than 1 'PermitOnly()' in Method with Imperative CAS!

Ask a question
Dan

Dan

14y
2.1k
1

Hi guys,

I have a bit of a problem which is that when setting up granular permissions imperatively within a method using CAS security classes, I am finding that I can only activate one of the classes with the 'PermitOnly()' option.

The problem this is causing is that I am trying to:

1.      Restrict the method to be only able to write to one directory. Which I can do with the 'PermitOnly()' option.

2.      I also want to use the user interface for debugging which requires me to add permissions for the UIPermissions class. The only way I'm aware of doing this is to create an instance of the class and, once again, call the 'PermitOnly()' method from it. Unfortunately, when doing this, the runtime throws an exception.

I have experiemented with other CAS security classes and the same is true with them as well. It seems that if you have more than one security class instance that that calls its 'PermitOnly()', the runtime throws an exception. This, of course is very, very awkward. Does anyone know why this is happening and if there is a way around it?

I should say that I am using Visual Studio C# 2008 Express Edition.

Below is one example of the type of code I am using:

 

  public void MyExtraMethod()
        {
            UIPermission uIPermission = new UIPermission(UIPermissionWindow.AllWindows);
            uIPermission.PermitOnly();
                                 
            FileIOPermission fileIOPermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, @"C:\MyDir\");
            fileIOPermission.PermitOnly();
                                   
            try
            {
                using (StreamWriter writer = new StreamWriter(@"C:\MyDir\HelloThere.Txt", true))
                {
                    writer.WriteLine("Hello there : )");
                }
            }
            catch
            {
                MessageBox.Show("Sorry, you do not have permission to\r\n write to the hard drive", "Security Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }