HOW TO:使用 RequestRefuse 旗標拒絕使用權限

更新:2007 年 11 月

如果您擔心程式碼可能會被用來惡意地存取系統資源,您可以要求永遠不接受特定的使用權限。例如,一個只瀏覽檔案資料但不會修改資料的應用程式,就可以拒絕任何的檔案寫入使用權限。在臭蟲或惡意攻擊的事件中,這個程式碼就不會危害它所在位置上的資料。

RequestRefuse 允許要求將一個大型的使用權限集合做為選擇性的使用權限,而確保某些特定的使用權限不在授與的範圍內。

以下的範例將使用 RequestRefuse 以拒絕一般語言執行階段安全性系統要求的 FileIOPermission

範例

Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Permissions
'The request is placed at the assembly level. 
<assembly: FileIOPermission(SecurityAction.RequestRefuse, Unrestricted := True)>

Namespace MyNameSpace
   Public Class MyClass1
      Public Sub New()
      End Sub
      
      Public Shared Sub Main()
         'Creation of the log is attempted in the try block.
         Try
            Dim TextStream As New StreamWriter("Log.txt")
            TextStream.WriteLine("This Log was created on {0}", DateTime.Now)
            TextStream.Close()
            Console.WriteLine("The Log was created")
         'Catch the Security exception and inform the user that the 
         'application was not granted FileIOPermission.
         Catch
            Console.WriteLine("This application does not have permission to write to the disk.")         
         End Try
      End Sub
   End Class
End Namespace
//The request is placed at the assembly level. 
using System.Security.Permissions;
[assembly:FileIOPermission(SecurityAction.RequestRefuse ,Unrestricted = true)]

namespace MyNameSpace
{
   using System;
   using System.Security;
   using System.Security.Permissions;
   using System.IO;

   public class MyClass
   {
      public MyClass()
     {       
     }
      
      public static int Main(string[] args)
      {
         //Creation of the log is attempted in the try block.
         try
         {   
            StreamWriter TextStream = new StreamWriter("Log.txt");
            TextStream.WriteLine("This Log was created on {0}", DateTime.Now);
            TextStream.Close();
            Console.WriteLine("The Log was created");
         }
         //Catch the Security exception and inform the user that the 
         //application was not granted FileIOPermission.
         catch(SecurityException)
        {
            Console.WriteLine("This application does not have permission to write to the disk.");
        }
      

         return 0;
      }
   }
}    

前述的範例並不接受使用權限而建立檔案並產生一個安全性例外狀況。其中的 catch 陳述式會攔截例外狀況,而應用程式也會在主控台上顯示以下的訊息:

This application does not have permission to write to the disk.

請參閱

概念

要求使用權限

其他資源

使用屬性擴充中繼資料

程式碼存取安全性