Share via


HOW TO:使用 RequestOptional 旗標要求選擇性使用權限

更新:2007 年 11 月

SecurityAction.RequestOptional 旗標可讓您要求使用權限集合,但卻會拒絕執行階段可能願意授與的其他所有使用權限。相反地,RequestRefuse 旗標則允許您以隱含指定不應將哪些使用權限授與給程式碼的方式,來拒絕這些使用權限。

相對於使用 RequestMinimum 旗標,您的應用程式如果未收到您使用 RequestOptional 要求的所有使用權限,它還是會執行,而且當您的應用程式嘗試存取受保護的資源時,將會擲回 SecurityException。如果您使用這類要求,您必須使您的程式碼可以擷取當您的程式碼未被授與該選擇性使用權限時,將擲回的任何例外狀況。

以下的範例說明使用 SecurityAction.RequestOptional 旗標要求 FileIOPermission,而間接拒絕其他所有權限。這個範例假設有一個存在於 LogNameSpace 的假設性類別 Log。類別 Log 包含 MakeLog 方法,用來建立本機電腦上的新日誌檔。這個應用程式將建立 Log 類別的新執行個體,並執行 try 區塊中的 MakeLog 方法。使用 catch 關鍵字以攔截任何擲回的 SecurityException 並顯示訊息。

範例

Imports System
Imports System.Security
'The hypothetical class log is in this namespace.
Imports LogNameSpace
Imports System.Security.Permissions
'The request is placed at the assembly level.
<assembly: FileIOPermission(SecurityAction.RequestOptional, Unrestricted := True)>

Namespace MyNamespace
   Public Class MyClass1
      
      Public Sub New()

      End Sub
      
      'Entry point that delegates to C-style main Private Function.
      Public Overloads Shared Sub Main()
         Main(System.Environment.GetCommandLineArgs())
      End Sub
      
      Overloads Public Shared Sub Main(args() As String)
         'Put any code that requires optional permissions in the try block. 
         Try
            Dim MyLog As New Log()
            MyLog.MakeLog()
            Console.WriteLine("The Log has been 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.RequestOptional, Unrestricted = true)]

namespace MyNamespace {
   using System;
   using System.Security;
   //The hypothetical class log is in this namespace.
   using LogNameSpace;

   public class MyClass {
      public MyClass() {
      }

      public static void Main(string[] args) {
         //Put any code that requires optional permissions in the try block. 
         try {
            Log MyLog = new Log();
            MyLog.MakeLog();
            Console.WriteLine("The Log has been 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.");
         }
      }
   }
}

前述的程式碼當它擁有足夠的使用權限時,即會建立日誌檔並在主控台 (Console) 上顯示以下的訊息:

The Log has been created.

如果程式碼是從共用裝置上執行,而本機安全設定也不允許這類的程式碼擁有 FileIOPermission 時,該程式碼將不會擁有足夠的使用權限並顯示以下的訊息:

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

請參閱

概念

要求使用權限

參考

SecurityAction

FileIOPermission

UIPermission

其他資源

使用屬性擴充中繼資料

程式碼存取安全性