共用方式為


HOW TO:使用 RequestMinimum 旗標要求最低使用權限

更新:2007 年 11 月

RequestMinimum 旗標可以讓您要求執行您的程式碼所需的最小使用權限集合。相反地,RequestRefuse 旗標則讓您透過明確指定程式碼不應授予的使用權限,拒絕這些使用權限。

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

下列範例會使用 RequestMinimum 旗標,要求 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.RequestMinimum, 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.RequestMinimum, 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

其他資源

使用屬性擴充中繼資料

程式碼存取安全性