次の方法で共有


FileIOPermission クラス

ファイルおよびフォルダにアクセスするための機能を制御します。このクラスは継承できません。

この型のすべてのメンバの一覧については、FileIOPermission メンバ を参照してください。

System.Object
   System.Security.CodeAccessPermission
      System.Security.Permissions.FileIOPermission

<Serializable>
NotInheritable Public Class FileIOPermission   Inherits CodeAccessPermission   Implements IUnrestrictedPermission
[C#]
[Serializable]
public sealed class FileIOPermission : CodeAccessPermission,   IUnrestrictedPermission
[C++]
[Serializable]
public __gc __sealed class FileIOPermission : public   CodeAccessPermission, IUnrestrictedPermission
[JScript]
public
   Serializable
class FileIOPermission extends CodeAccessPermission   implements IUnrestrictedPermission

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

このアクセス許可は、 FileIOPermissionAccess によって提供される、次の 4 種類のファイル IO アクセスに区別されます。

  • Read: ファイルの内容を読み取るために必要なアクセス権、またはファイルの長さや最終更新時刻などの情報へのアクセス権。
  • Write: ファイルの内容に書き込むために必要なアクセス権、またはファイル名などのファイルに関する情報を変更するために必要なアクセス権。削除および上書きもできます。
  • Append: ファイルの末尾に書き込むために必要なアクセス権。読み取ることはできません。
  • PathDiscovery: パス自体に存在する情報へのアクセス。これにより、ユーザー名などのパス中の機密情報だけではなく、パスによって判明するディレクトリ構造についての情報も保護されます。この値は、パスによって表されたファイルまたはフォルダへのアクセスを与えません。

これらのアクセス許可はすべて独立しています。つまり、あるアクセス許可に別のアクセス許可は含まれません。たとえば、 Write アクセス許可に Read アクセス許可または Append アクセス許可は含まれません。複数のアクセス許可が必要な場合は、次のコード例で示すように、ビットごとの OR を使用して結合できます。ファイルのアクセス許可は、標準絶対パスで定義されます。呼び出しは、常に標準のファイル パスで行う必要があります。

FileIOPermission は、ファイルおよびフォルダの操作に対する保護方法を管理します。 File クラスは、ファイルおよびフォルダに対する安全なアクセスを提供します。ファイルへのハンドルが作成されると、セキュリティ アクセス チェックが実行されます。作成時にこのチェックを行うことによって、セキュリティ チェックのパフォーマンスに与える影響が最小限になります。ファイルを開く回数は 1 回ですが、ファイルを開いている間に読み取りと書き込みは何度も行うことができます。ファイルが開かれた後は、チェックは行われません。信頼関係のない呼び出し元にオブジェクトが渡された場合は、渡されたオブジェクトが不正使用される可能性があります。たとえば、ファイル ハンドルは、低いアクセス許可しか持たないコードでもアクセスできるパブリック グローバル スタティックスには格納しないでください。

FileIOPermissionAccess は、ファイルまたはフォルダで実行できるアクションを指定します。また、これらのアクションは、ビットごとの OR を使用して結合すると、複雑なインスタンスを形成できます。

フォルダへのアクセスとは、そのフォルダが格納しているすべてのファイルへのアクセス、およびそのサブフォルダ内のすべてのファイルとフォルダへのアクセスを意味します。たとえば、C:\folder1\ への Read アクセスは、C:\folder1\file1.txt、C:\folder1\folder2\、C:\folder1\folder2\file2.txt などへの Read アクセスを意味します。

注意    Unrestricted FileIOPermission は、1 つのファイルにアクセスするための複数のパス名も含め、ファイル システム内のすべてのパスに対するアクセス許可を与えます。ファイルへのアクセスを Deny によって拒否するには、そのファイルへの有効なパスをすべて Deny によって拒否する必要があります。たとえば、\\server\share をネットワーク ドライブ X に割り当てた場合、\\server\share\file へのアクセスを Deny によって拒否するには、そのファイルにアクセスするために使用できる \\server\share\file、X:\file などのパスをすべて Deny によって拒否する必要があります。複数のパスを使用する場合は、 PermitOnlyDeny を組み合わせて使用することをお勧めします。この例では、\\server\share に対して PermitOnly を適用してから、\\server\share\file に対して Deny を適用して、代替のパスを完全に排除できます。この詳細および DenyPermitOnly を使用する場合の詳細については、「 Deny 」の Canonicalization Problems Using Deny を参照してください。

メモ   \\server\share\bogusfolder\..\file の形式のパスはセキュリティ システムによって \\server\share\file のような正規形式に変換されます。したがって、 Deny を使用するときは、\\server\share\file のような正規形式のパスだけを対象にすればよく、同じパスを示す他の表記形式を考慮する必要はありません。

メモ    Deny は、Windows NTFS ファイル システムで使用した場合に最も効果を発揮します。NTFS のセキュリティ機能は、FAT32 よりも大幅に優れています。NTFS の詳細については、Windows のマニュアルを参照してください。

使用例

[Visual Basic, C#, C++] FileIOPermission を使用するコードを次の例に示します。次の 2 行のコードの後で、オブジェクト f は、クライアント コンピュータのローカル ディスク上のすべてのファイルを読み取るためのアクセス許可を表します。

 
Dim f As New FileIOPermission(PermissionState.None)
f.AllLocalFiles = FileIOPermissionAccess.Read

[C#] 
FileIOPermission f = new FileIOPermission(PermissionState.None);
f.AllLocalFiles = FileIOPermissionAccess.Read;

[C++] 
FileIOPermission* f = new FileIOPermission(PermissionState::None);
f->AllLocalFiles = FileIOPermissionAccess::Read;

[Visual Basic, C#, C++] 次の 2 行のコードの後で、オブジェクト f2 は、C:\test_r を読み取るためのアクセス許可と C:\example\out.txt に対する読み取りと書き込みのためのアクセス許可を表します。 ReadWrite は、前述のとおり、ファイルおよびフォルダのアクセス許可を表します。

 
Dim f2 As New FileIOPermission(FileIOPermissionAccess.Read, "C:\test_r")
f2.AddPathList(FileIOPermissionAccess.Write Or _
   FileIOPermissionAccess.Read, "C:\example\out.txt")

[C#] 
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");

[C++] 
FileIOPermission* f2 = new FileIOPermission(FileIOPermissionAccess::Read, S"C:\\test_r");
f2->AddPathList(static_cast<FileIOPermissionAccess>(FileIOPermissionAccess::Write | FileIOPermissionAccess::Read),
                S"C:\\example\\out.txt");

[Visual Basic, C#, C++] FileIOPermission のさまざまなメンバの使用例を次に示します。

 
' This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml, FromXml, 
' GetPathList and SetPathList methods, and the AllFiles and AllLocalFiles properties  
' of the FileIOPermission class.

Imports System
Imports System.Security
Imports System.Security.Permissions
Imports System.Collections
Imports Microsoft.VisualBasic

<Assembly: CLSCompliant(True)> 

Public Class FileIOPermissionDemo

    ' IsSubsetOf determines whether the current permission is a subset of the specified permission.
    ' This method compares various FileIOPermission paths with FileIOPermissionAccess set to AllAccess.
    Private Function IsSubsetOfDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim fileIO1, fileIO2 As String
        Dim fileIOPerm1, fileIOPerm2 As FileIOPermission

        Dim fileIOGen1 As New FileIOGenerator()
        Dim fileIOGen2 As New FileIOGenerator()

        fileIOGen1.ResetIndex()
        While fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, FileIOPermissionAccess.AllAccess)
            If fileIOPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)

            fileIOGen2.ResetIndex()

            While fileIOGen2.CreateFilePath(fileIOPerm2, fileIO2, FileIOPermissionAccess.AllAccess)
                Dim firstPermission As String = IIf(fileIO1 = "" Or fileIO1 Is Nothing, "null", fileIO1)
                Dim secondPermission As String = IIf(fileIO2 = "" Or fileIO2 Is Nothing, "null", fileIO2)
                If fileIOPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                Try
                    If fileIOPerm1.IsSubsetOf(fileIOPerm2) Then

                        Console.WriteLine((firstPermission & " is a subset of " & secondPermission & ControlChars.Lf))
                    Else
                        Console.WriteLine((firstPermission & " is not a subset of " & secondPermission & ControlChars.Lf))
                    End If

                Catch e As Exception
                    Console.WriteLine(IIf("An exception was thrown for subset :" & fileIO1 = "", "null", IIf(fileIO1 & ControlChars.Lf & fileIO2 = "", "null", fileIO2 & ControlChars.Lf & e.ToString())))
                End Try
ContinueWhile2:
            End While
ContinueWhile1:
        End While
        Return returnValue
    End Function 'IsSubsetOfDemo

    ' Union creates a new permission that is the union of the current permission and the specified permission.
    Private Function UnionDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim fileIO1, fileIO2 As String
        Dim fileIOPerm1, fileIOPerm2 As FileIOPermission
        Dim fileIOPerm3 As IPermission

        Dim fileIOGen1 As New FileIOGenerator()
        Dim fileIOGen2 As New FileIOGenerator()

        fileIOGen1.ResetIndex()
        While fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, FileIOPermissionAccess.Read)
            If fileIO1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            fileIOGen2.ResetIndex()

            While fileIOGen2.CreateFilePath(fileIOPerm2, fileIO2, FileIOPermissionAccess.Read)

                Try
                    If fileIOPerm2 Is Nothing Then
                        GoTo ContinueWhile2
                    End If
                    Dim firstPermission As String = IIf(fileIO1 = "" Or fileIO1 Is Nothing, "null", fileIO1)
                    Dim secondPermission As String = IIf(fileIO2 = "" Or fileIO2 Is Nothing, "null", fileIO2)
                    fileIOPerm3 = CType(fileIOPerm1.Union(fileIOPerm2), FileIOPermission)
                    fileIOPerm3 = fileIOPerm1.Union(fileIOPerm2)

                    If fileIOPerm3 Is Nothing Then
                        Console.WriteLine(("The union of " & firstPermission & "  and " & secondPermission & " is null."))
                    Else
                        Console.WriteLine(("The union of " & firstPermission & "  and " & secondPermission & " = " & ControlChars.Lf & ControlChars.Tab & CType(fileIOPerm3, FileIOPermission).GetPathList(FileIOPermissionAccess.Read)(0)))
                    End If
                Catch e As Exception
                    Console.WriteLine(("An exception was thrown for union " & e.ToString()))
                    returnValue = False
                End Try
ContinueWhile2:
            End While
ContinueWhile1:
        End While


        Return returnValue
    End Function 'UnionDemo

    ' Intersect creates and returns a new permission that is the intersection of the current 
    ' permission and the permission specified.
    Private Function IntersectDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim fileIO1, fileIO2 As String
        Dim fileIOPerm1, fileIOPerm2, fileIOPerm3 As FileIOPermission

        Dim fileIOGen1 As New FileIOGenerator()
        Dim fileIOGen2 As New FileIOGenerator()

        fileIOGen1.ResetIndex()
        While fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, FileIOPermissionAccess.Read)
            If fileIO1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            fileIOGen2.ResetIndex()

            While fileIOGen2.CreateFilePath(fileIOPerm2, fileIO2, FileIOPermissionAccess.Read)
                If fileIOPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                Dim firstPermission As String = IIf(fileIO1 = "" Or fileIO1 Is Nothing, "null", fileIO1)
                Dim secondPermission As String = IIf(fileIO2 = "" Or fileIO2 Is Nothing, "null", fileIO2)
                Try

                    fileIOPerm3 = CType(fileIOPerm1.Intersect(fileIOPerm2), FileIOPermission)
                    If Not (fileIOPerm3 Is Nothing) AndAlso Not (fileIOPerm3.GetPathList(FileIOPermissionAccess.Read) Is Nothing) Then

                        Console.WriteLine(("The intersection of " & firstPermission & "  and " & ControlChars.Lf & ControlChars.Tab & secondPermission & " = " & ControlChars.Lf & ControlChars.Tab & CType(fileIOPerm3, FileIOPermission).GetPathList(FileIOPermissionAccess.Read)(0)))
                    Else
                        Console.WriteLine(("The intersection of " & firstPermission & "  and " & secondPermission & " is null."))
                    End If
                Catch e As Exception
                    Console.WriteLine(("An exception was thrown for intersection " & e.ToString()))
                    returnValue = False
                End Try
ContinueWhile2:
            End While
ContinueWhile1:
        End While

        Return returnValue
    End Function 'IntersectDemo

    'Copy creates and returns an identical copy of the current permission.
    Private Function CopyDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim fileIO1 As String
        Dim fileIOPerm1, fileIOPerm2 As FileIOPermission
        Dim fileIOGen1 As New FileIOGenerator()
        Dim fileIOGen2 As New FileIOGenerator()

        fileIOGen1.ResetIndex()
        While fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, FileIOPermissionAccess.Read)
            If fileIO1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            fileIOGen2.ResetIndex()
            Try
                fileIOPerm2 = CType(fileIOPerm1.Copy(), FileIOPermission)
                If Not (fileIOPerm2 Is Nothing) Then
                    Console.WriteLine(("Result of copy = " & fileIOPerm2.ToString() & ControlChars.Lf))
                Else
                    Console.WriteLine("Result of copy is null. " & ControlChars.Lf)
                End If
            Catch e As Exception
                If (True.ToString()) Then
                    If fileIO1 = "" Then
                        Console.WriteLine("The target FileIOPermission is empty, copy failed.")

                    Else
                        Console.WriteLine(e.ToString())
                    End If
                End If
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While
        Return returnValue
    End Function 'CopyDemo

    ' ToXml creates an XML encoding of the permission and its current state; 
    ' FromXml reconstructs a permission with the specified state from the XML encoding. 
    Private Function ToFromXmlDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim fileIO1 As String
        Dim fileIOPerm1, fileIOPerm2 As FileIOPermission

        Dim fileIOGen1 As New FileIOGenerator()
        Dim fileIOGen2 As New FileIOGenerator()

        fileIOGen1.ResetIndex()
        While fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, FileIOPermissionAccess.Read)
            If fileIOPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("********************************************************" & ControlChars.Lf)
            fileIOGen2.ResetIndex()
            Try
                fileIOPerm2 = New FileIOPermission(PermissionState.None)
                fileIOPerm2.FromXml(fileIOPerm1.ToXml())
                Console.WriteLine(("Result of ToFromXml = " & fileIOPerm2.ToString() & ControlChars.Lf))

            Catch e As Exception
                Console.WriteLine(("ToFromXml failed :" & fileIOPerm1.ToString() & e.ToString()))
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While

        Return returnValue
    End Function 'ToFromXmlDemo

    ' AddPathList adds access for the specified files and directories to the existing state of the permission.
    ' SetPathList sets the specified access to the specified files and directories, replacing the existing state 
    ' of the permission.
    ' GetPathList gets all files and directories that have the specified FileIOPermissionAccess.
    Private Function SetGetPathListDemo() As Boolean
        Try
            Console.WriteLine("********************************************************" & ControlChars.Lf)

            Dim fileIOPerm1 As FileIOPermission
            Console.WriteLine("Creating a FileIOPermission with AllAccess rights for 'C:\Examples\Test\TestFile.txt")
            fileIOPerm1 = New FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\Examples\Test\TestFile.txt")
            Console.WriteLine("Adding 'C:\Temp' to the write access list, and " & ControlChars.Lf & " 'C:\Examples\Test' to read access.")
            fileIOPerm1.AddPathList(FileIOPermissionAccess.Write, "C:\Temp")
            fileIOPerm1.AddPathList(FileIOPermissionAccess.Read, "C:\Examples\Test")
            Dim paths As String() = fileIOPerm1.GetPathList(FileIOPermissionAccess.Read)
            Console.WriteLine("Read access before SetPathList = ")
            Dim path As String
            For Each path In paths
                Console.WriteLine((ControlChars.Tab & path))
            Next path
            Console.WriteLine("Setting the read access list to " & ControlChars.Lf & "'C:\Temp'")
            fileIOPerm1.SetPathList(FileIOPermissionAccess.Read, "C:\Temp")
            paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Read)
            Console.WriteLine("Read access list after SetPathList = ")
            For Each path In paths
                Console.WriteLine((ControlChars.Tab & path))
            Next path

            paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Write)
            Console.WriteLine("Write access list after SetPathList = ")
            For Each path In paths
                Console.WriteLine((ControlChars.Tab & path))
            Next path

            Dim pathList() As String
            pathList = fileIOPerm1.GetPathList(FileIOPermissionAccess.AllAccess)

        Catch e As ArgumentException
            ' FileIOPermissionAccess.AllAccess can not be used as a parameter for GetPathList.
            Console.WriteLine(("An ArgumentException occurred as a result of using AllAccess. " & "This property cannot be used as a parameter in GetPathList " & "because it represents more than one type of file variable access. : " & ControlChars.Lf & e.ToString()))
        End Try

        Return True
    End Function 'SetGetPathListDemo

    ' The AllFiles property gets or sets the permitted access to all files.
    ' The AllLocalFiles property gets or sets the permitted access to all local files.
    Private Function AllFilesDemo() As Boolean
        Try
            Console.WriteLine("********************************************************" & ControlChars.Lf)

            Dim fileIOPerm1 As FileIOPermission
            Console.WriteLine("Creating a FileIOPermission and adding read access for all files")
            fileIOPerm1 = New FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\Examples\Test\TestFile.txt")
            fileIOPerm1.AllFiles = FileIOPermissionAccess.Read
            Console.WriteLine("AllFiles access = " & fileIOPerm1.AllFiles.ToString())
            Console.WriteLine("Adding AllAccess rights for local files.")
            fileIOPerm1.AllLocalFiles = FileIOPermissionAccess.AllAccess
            Console.WriteLine("AllLocalFiles access = " & fileIOPerm1.AllLocalFiles.ToString())

        Catch e As ArgumentException
            Console.WriteLine(e.ToString())
            Return False
        End Try

        Return True
    End Function 'AllFilesDemo

    ' Invoke all demos.
    Public Function RunDemo() As Boolean

        Dim ret As Boolean = True
        Dim retTmp As Boolean
        ' Call the IsSubsetOfPath demo.
        retTmp = IsSubsetOfDemo()
        If retTmp Then
            Console.Out.WriteLine("IsSubsetOf demo completed successfully.")
        Else
            Console.Out.WriteLine("IsSubsetOf demo failed.")
        End If
        ret = retTmp AndAlso ret

        ' Call the Union demo.
        retTmp = UnionDemo()
        If retTmp Then
            Console.Out.WriteLine("Union demo completed successfully.")
        Else
            Console.Out.WriteLine("Union demo failed.")
        End If
        ret = retTmp AndAlso ret

        ' Call the Intersect demo.    
        retTmp = IntersectDemo()
        If retTmp Then
            Console.Out.WriteLine("Intersect demo completed successfully.")
        Else
            Console.Out.WriteLine("Intersect demo failed.")
        End If
        ret = retTmp AndAlso ret


        ' Call the Copy demo.
        retTmp = CopyDemo()
        If retTmp Then
            Console.Out.WriteLine("Copy demo completed successfully.")
        Else
            Console.Out.WriteLine("Copy demo failed.")
        End If
        ret = retTmp AndAlso ret

        ' Call the ToFromXml demo.    
        retTmp = ToFromXmlDemo()
        If retTmp Then
            Console.Out.WriteLine("ToFromXml demo completed successfully.")
        Else
            Console.Out.WriteLine("ToFromXml demo failed.")
        End If
        ret = retTmp AndAlso ret

        ' Call the SetGetPathList demo.    
        retTmp = SetGetPathListDemo()
        If retTmp Then
            Console.Out.WriteLine("SetGetPathList demo completed successfully.")
        Else
            Console.Out.WriteLine("SetGetPathList demo failed.")
        End If
        ret = retTmp AndAlso ret

        ' Call the AllFiles demo.    
        retTmp = AllFilesDemo()
        If retTmp Then
            Console.Out.WriteLine("AllFiles demo completed successfully.")
        Else
            Console.Out.WriteLine("AllFiles demo failed.")
        End If
        ret = retTmp AndAlso ret

        Return ret
    End Function 'RunDemo

    ' Test harness.
    Public Overloads Shared Sub Main(ByVal args() As [String])
        Try
            Dim democase As New FileIOPermissionDemo()
            Dim ret As Boolean = democase.RunDemo()
            If ret Then
                Console.Out.WriteLine("FileIOPermission demo completed successfully.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 100
            Else
                Console.Out.WriteLine("FileIOPermission demo failed.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 101
            End If
        Catch e As Exception
            Console.Out.WriteLine("FileIOPermission demo failed")
            Console.WriteLine(e.ToString())
            Console.Out.WriteLine("Press the Enter key to exit.")
            Dim consoleInput As String = Console.ReadLine()
            System.Environment.ExitCode = 101
        End Try
    End Sub 'Main
End Class 'FileIOPermissionDemo


' This class generates FileIOPermission objects.

Friend Class FileIOGenerator


    Private myFile As String() = {"C:\Examples\Test\TestFile.txt", "C:\Examples\Test\", "C:\Examples\Test\..", "C:\Temp"}

    Private myAccess As FileIOPermissionAccess() = {FileIOPermissionAccess.AllAccess, FileIOPermissionAccess.Append, FileIOPermissionAccess.NoAccess, FileIOPermissionAccess.PathDiscovery, FileIOPermissionAccess.Read, FileIOPermissionAccess.Write}

    Private fileIndex As Integer = 0


    Public Sub New()

        ResetIndex()
    End Sub 'New


    Public Sub ResetIndex()
        fileIndex = 0
    End Sub 'ResetIndex

    ' Create a FileIOPermission using FileIOPermissionAccess that is passed in.
    Public Function CreateFilePath(ByRef fileIOPerm As FileIOPermission, ByRef file As String, ByVal fpa As FileIOPermissionAccess) As Boolean

        If fileIndex = myFile.Length Then
            fileIOPerm = New FileIOPermission(PermissionState.None)
            file = ""
            fileIndex &= 1
            Return True
        End If
        If fileIndex > myFile.Length Then
            fileIOPerm = Nothing
            file = ""
            Return False
        End If

        file = myFile(fileIndex)
        fileIndex = fileIndex + 1

        Try
            fileIOPerm = New FileIOPermission(fpa, file.ToString())
            Return True
        Catch e As Exception
            Console.WriteLine(("Cannot create FileIOPermission: " & file & " " & e.ToString()))
            fileIOPerm = New FileIOPermission(PermissionState.None)
            file = ""
            Return True
        End Try
    End Function 'CreateFilePath
End Class 'FileIOGenerator 
' End of FileIOGenerator.

[C#] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml, FromXml, 
// GetPathList and SetPathList methods, and the AllFiles and AllLocalFiles properties  
// of the FileIOPermission class.


using System;
using System.Security; 
using System.Security.Permissions; 
using System.Collections;

[assembly:CLSCompliant(true)]

public class FileIOPermissionDemo
{
// IsSubsetOf determines whether the current permission is a subset of the specified permission.
// This method compares various FileIOPermission paths with FileIOPermissionAccess set to AllAccess.
    private bool IsSubsetOfDemo()
    {

        bool returnValue = true;

        string fileIO1,fileIO2;
        FileIOPermission fileIOPerm1,fileIOPerm2;

        FileIOGenerator fileIOGen1 = new FileIOGenerator();
        FileIOGenerator fileIOGen2 = new FileIOGenerator();

        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(out fileIOPerm1, out fileIO1, FileIOPermissionAccess.AllAccess)) 
        {
            if(fileIOPerm1 == null) continue;

            Console.WriteLine("**********************************************************\n");

            fileIOGen2.ResetIndex();

            while(fileIOGen2.CreateFilePath(out fileIOPerm2, out fileIO2, FileIOPermissionAccess.AllAccess)) 
            {
                string firstPermission = fileIO1 == "" | fileIO1 == null ? "null" : fileIO1 ;
                string secondPermission = fileIO2 == "" | fileIO2 == null ? "null" : fileIO2;
                if(fileIOPerm2 == null) continue;
                try
                {            
                    if (fileIOPerm1.IsSubsetOf(fileIOPerm2))
                    {
                            
                        Console.WriteLine(firstPermission +" is a subset of " + secondPermission + "\n");
                    }
                    else
                    {
                        Console.WriteLine(firstPermission  +" is not a subset of " + secondPermission + "\n");
                    }

                }
                catch(Exception e) 
                {
                    Console.WriteLine("An exception was thrown for subset :" + fileIO1 == "" ? "null" : fileIO1 + "\n" + 
                        fileIO2 == "" ? "null" : fileIO2 +"\n" + e);
                }
            }
        }
        return returnValue;
    }
// Union creates a new permission that is the union of the current permission and the specified permission.
    private bool UnionDemo()
    {

        bool returnValue = true;

        string fileIO1,fileIO2;
        FileIOPermission fileIOPerm1,fileIOPerm2;
        IPermission fileIOPerm3;

        FileIOGenerator fileIOGen1 = new FileIOGenerator();
        FileIOGenerator fileIOGen2 = new FileIOGenerator();

        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(out fileIOPerm1, out fileIO1, FileIOPermissionAccess.Read)) 
        {
            if(fileIO1 == null) continue;
                
            Console.WriteLine("**********************************************************\n");
            fileIOGen2.ResetIndex();

            while(fileIOGen2.CreateFilePath(out fileIOPerm2, out fileIO2, FileIOPermissionAccess.Read)) 
            {

                try
                {
                    if(fileIOPerm2 == null) continue;

                    string firstPermission = fileIO1 == "" | fileIO1 == null ? "null" : fileIO1 ;
                    string secondPermission = fileIO2 == "" | fileIO2 == null ? "null" : fileIO2;
                    fileIOPerm3 = (FileIOPermission)fileIOPerm1.Union(fileIOPerm2);
                    fileIOPerm3 = fileIOPerm1.Union(fileIOPerm2);

                    if(fileIOPerm3 == null) 
                    {
                        Console.WriteLine("The union of " + firstPermission + "  and "  + secondPermission + " is null.");
                    }
                    else
                    {
                        Console.WriteLine("The union of " + firstPermission + "  and "  + secondPermission + 
                            " = \n\t" + ((FileIOPermission)fileIOPerm3).GetPathList(FileIOPermissionAccess.Read)[0]);
                    }
                }
                catch(Exception e) 
                {
                    Console.WriteLine("An exception was thrown for union " + e);
                    returnValue=false;
                }

            }
                
        }

        return returnValue;

    }

// Intersect creates and returns a new permission that is the intersection of the current 
// permission and the permission specified.
    private bool IntersectDemo()
    {

        bool returnValue = true;

        string fileIO1,fileIO2;
        FileIOPermission fileIOPerm1,fileIOPerm2,fileIOPerm3;

        FileIOGenerator fileIOGen1 = new FileIOGenerator();
        FileIOGenerator fileIOGen2 = new FileIOGenerator();

        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(out fileIOPerm1, out fileIO1, FileIOPermissionAccess.Read)) 
        {
            if(fileIO1 == null) continue;
            Console.WriteLine("**********************************************************\n");
            fileIOGen2.ResetIndex();

            while(fileIOGen2.CreateFilePath(out fileIOPerm2, out fileIO2, FileIOPermissionAccess.Read)) 
            {
                if(fileIOPerm2 == null) continue;
                string firstPermission = fileIO1 == "" | fileIO1 == null ? "null" : fileIO1 ;
                string secondPermission = fileIO2 == "" | fileIO2 == null ? "null" : fileIO2;
                try
                {
            
                    fileIOPerm3 = (FileIOPermission)fileIOPerm1.Intersect(fileIOPerm2);
                    if (fileIOPerm3 != null && fileIOPerm3.GetPathList(FileIOPermissionAccess.Read) != null)
                    {

                        Console.WriteLine("The intersection of " + firstPermission + "  and \n\t"  + secondPermission + 
                            " = \n\t" + ((FileIOPermission)fileIOPerm3).GetPathList(FileIOPermissionAccess.Read)[0]);
                    }
                    else
                    {
                        Console.WriteLine("The intersection of " + firstPermission + "  and "  + secondPermission + " is null.");
                    }
                }
                catch(Exception e) 
                {
                    Console.WriteLine("An exception was thrown for intersection "  + e);
                    returnValue=false;
                }
            }
        }

        return returnValue;

    }
//Copy creates and returns an identical copy of the current permission.
    private bool CopyDemo()
    {
        bool returnValue = true;
        string fileIO1;
        FileIOPermission fileIOPerm1,fileIOPerm2;
        FileIOGenerator fileIOGen1 = new FileIOGenerator();
        FileIOGenerator fileIOGen2 = new FileIOGenerator();

        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(out fileIOPerm1, out fileIO1, FileIOPermissionAccess.Read)) 
        {
            if(fileIO1 == null ) continue;  
            Console.WriteLine("**********************************************************\n");
            fileIOGen2.ResetIndex();
            try
            {            
                fileIOPerm2 = (FileIOPermission)fileIOPerm1.Copy();
                if (fileIOPerm2 != null)
                {
                    Console.WriteLine("Result of copy = " + fileIOPerm2.ToString() + "\n");
                }
                else
                {
                    Console.WriteLine("Result of copy is null. \n");
                }
            }
            catch(Exception e) 
            {
            {
                if (fileIO1 == "")
                {
                    Console.WriteLine( "The target FileIOPermission is empty, copy failed.");

                }
                else
                    Console.WriteLine( e);
            }
                continue;
            }
        }
        return returnValue;
    }
// ToXml creates an XML encoding of the permission and its current state; 
// FromXml reconstructs a permission with the specified state from the XML encoding. 
    private bool ToFromXmlDemo()
    {

        bool returnValue = true;

        string fileIO1;
        FileIOPermission fileIOPerm1,fileIOPerm2;

        FileIOGenerator fileIOGen1 = new FileIOGenerator();
        FileIOGenerator fileIOGen2 = new FileIOGenerator();

        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(out fileIOPerm1, out fileIO1, FileIOPermissionAccess.Read)) 
        {
            if(fileIOPerm1 == null) continue;
            Console.WriteLine("********************************************************\n");
            fileIOGen2.ResetIndex();
            try
            {            
                fileIOPerm2= new FileIOPermission(PermissionState.None);
                fileIOPerm2.FromXml(fileIOPerm1.ToXml());
                Console.WriteLine("Result of ToFromXml = " +fileIOPerm2.ToString() + "\n");
            
            }
            catch(Exception e) 
            {
                Console.WriteLine("ToFromXml failed :" + fileIOPerm1.ToString() + e);
                continue;
            }
        }

        return returnValue;

    }
// AddPathList adds access for the specified files and directories to the existing state of the permission.
// SetPathList sets the specified access to the specified files and directories, replacing the existing state 
// of the permission.
// GetPathList gets all files and directories that have the specified FileIOPermissionAccess.
    private bool SetGetPathListDemo()
    {
        try
        {
            Console.WriteLine("********************************************************\n");

            FileIOPermission fileIOPerm1;
            Console.WriteLine("Creating a FileIOPermission with AllAccess rights for 'C:\\Examples\\Test\\TestFile.txt");
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\Examples\\Test\\TestFile.txt");
            Console.WriteLine("Adding 'C:\\Temp' to the write access list, and \n 'C:\\Examples\\Test' to read access.");
            fileIOPerm1.AddPathList(FileIOPermissionAccess.Write, "C:\\Temp");
            fileIOPerm1.AddPathList(FileIOPermissionAccess.Read, "C:\\Examples\\Test");
            string[] paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Read);
            Console.WriteLine("Read access before SetPathList = ");
            foreach (string path in paths)
            {
                Console.WriteLine("\t" + path);
            }
            Console.WriteLine("Setting the read access list to \n'C:\\Temp'");
            fileIOPerm1.SetPathList(FileIOPermissionAccess.Read, "C:\\Temp");
            paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Read);
            Console.WriteLine("Read access list after SetPathList = ");
            foreach (string path in paths)
            {
                Console.WriteLine("\t" + path);
            }

            paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Write);
            Console.WriteLine("Write access list after SetPathList = ");
            foreach (string path in paths)
            {
                Console.WriteLine("\t" + path);
            }

            Console.WriteLine("Write access = \n" + 
                fileIOPerm1.GetPathList(FileIOPermissionAccess.AllAccess));

        }
        catch (ArgumentException e)
        {
            // FileIOPermissionAccess.AllAccess can not be used as a parameter for GetPathList.
            Console.WriteLine("An ArgumentException occurred as a result of using AllAccess. "  
                + "This property cannot be used as a parameter in GetPathList "
                + "because it represents more than one type of file variable access. : \n" + e);
        }

        return true;        
    }
// The AllFiles property gets or sets the permitted access to all files.
// The AllLocalFiles property gets or sets the permitted access to all local files.
    private bool AllFilesDemo()
    {
        try
        {
            Console.WriteLine("********************************************************\n");

            FileIOPermission fileIOPerm1;
            Console.WriteLine("Creating a FileIOPermission and adding read access for all files");
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\Examples\\Test\\TestFile.txt");
            fileIOPerm1.AllFiles = FileIOPermissionAccess.Read;
            Console.WriteLine("AllFiles access = " + fileIOPerm1.AllFiles);
            Console.WriteLine("Adding AllAccess rights for local files.");
            fileIOPerm1.AllLocalFiles = FileIOPermissionAccess.AllAccess;
            Console.WriteLine("AllLocalFiles access = " + fileIOPerm1.AllLocalFiles);

        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
            return false;
        }

        return true;        
    }
// Invoke all demos.
    public bool RunDemo()
    {

        bool ret=true;
        bool retTmp;
        // Call the IsSubsetOfPath demo.
        if(retTmp= IsSubsetOfDemo())Console.Out.WriteLine("IsSubsetOf demo completed successfully.");
        else Console.Out.WriteLine("IsSubsetOf demo failed.");
        ret=retTmp && ret;
    
        // Call the Union demo.
        if(retTmp= UnionDemo())Console.Out.WriteLine("Union demo completed successfully.");
        else Console.Out.WriteLine("Union demo failed.");
        ret=retTmp && ret;

        // Call the Intersect demo.    
        if(retTmp= IntersectDemo())Console.Out.WriteLine("Intersect demo completed successfully.");
        else Console.Out.WriteLine("Intersect demo failed.");
        ret=retTmp && ret;


        // Call the Copy demo.    
        if(retTmp= CopyDemo())Console.Out.WriteLine("Copy demo completed successfully.");
        else Console.Out.WriteLine("Copy demo failed.");
        ret=retTmp && ret;
        
        // Call the ToFromXml demo.    
        if(retTmp= ToFromXmlDemo())Console.Out.WriteLine("ToFromXml demo completed successfully.");
        else Console.Out.WriteLine("ToFromXml demo failed.");
        ret=retTmp && ret;

        // Call the SetGetPathList demo.    
        if(retTmp= SetGetPathListDemo())Console.Out.WriteLine("SetGetPathList demo completed successfully.");
        else Console.Out.WriteLine("SetGetPathList demo failed.");
        ret=retTmp && ret;

        // Call the AllFiles demo.    
        if(retTmp= AllFilesDemo())Console.Out.WriteLine("AllFiles demo completed successfully.");
        else Console.Out.WriteLine("AllFiles demo failed.");
        ret=retTmp && ret;

        return (  ret );    

    }
// Test harness.
    public static void Main(String[] args) 
    {
        try
        {
            FileIOPermissionDemo democase = new FileIOPermissionDemo();
            bool ret = democase.RunDemo();
            if (ret)
            {
                Console.Out.WriteLine("FileIOPermission demo completed successfully.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 100;
            }
            else
            {
                Console.Out.WriteLine("FileIOPermission demo failed.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 101;
            }
        }
        catch(Exception e)
        {
            Console.Out.WriteLine("FileIOPermission demo failed");
            Console.WriteLine(e.ToString());
            Console.Out.WriteLine("Press the Enter key to exit.");
            string consoleInput = Console.ReadLine();
            System.Environment.ExitCode = 101;
        }
    }
}


    // This class generates FileIOPermission objects.
 
internal  class FileIOGenerator
{


    private string[] myFile = 
    {
        "C:\\Examples\\Test\\TestFile.txt", 
        "C:\\Examples\\Test\\",
        "C:\\Examples\\Test\\..",
        "C:\\Temp"
    };

    private FileIOPermissionAccess[] myAccess = 
    {
        FileIOPermissionAccess.AllAccess,
        FileIOPermissionAccess.Append,
        FileIOPermissionAccess.NoAccess,
        FileIOPermissionAccess.PathDiscovery,
        FileIOPermissionAccess.Read,
        FileIOPermissionAccess.Write
    };

    private int fileIndex = 0;

    public FileIOGenerator()
    {

        ResetIndex();
    }

    public void ResetIndex()
    {
        fileIndex = 0;
    }
// Create a FileIOPermission using FileIOPermissionAccess that is passed in.
    public bool CreateFilePath(out FileIOPermission fileIOPerm, out string file, FileIOPermissionAccess fpa)
    {

        if(fileIndex == myFile.Length) 
        {
            fileIOPerm = new FileIOPermission(PermissionState.None);
            file="";
            fileIndex++;
            return true;

        }
        if(fileIndex > myFile.Length) 
        {
            fileIOPerm = null;
            file = "";
            return false;
        }

        file = myFile[fileIndex++];

        try
        {
            fileIOPerm = new FileIOPermission(fpa, file);
            return true;
        } 
        catch(Exception e)
        {
            Console.WriteLine("Cannot create FileIOPermission: " + file +" "+e);
            fileIOPerm = new FileIOPermission(PermissionState.None);
            file="";
            return true;
        }
    }
} // End of FileIOGenerator.


[C++] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml, FromXml, 
// GetPathList and SetPathList methods, and the AllFiles and AllLocalFiles properties  
// of the FileIOPermission class.

#using <mscorlib.dll>
using namespace System::Runtime::InteropServices;
using namespace System;
using namespace System::Security; 
using namespace System::Security::Permissions; 
using namespace System::Collections;

[assembly:CLSCompliant(true)];

// This class generates FileIOPermission objects.

private __gc class FileIOGenerator
{
private:
    String* myFile[];
    FileIOPermissionAccess myAccess[];
    int fileIndex;

public:
    FileIOGenerator()
    {
        String* tempFile[] = 
        {
            S"C:\\Examples\\Test\\TestFile.txt", 
                S"C:\\Examples\\Test\\",
                S"C:\\Examples\\Test\\..",
                S"C:\\Temp"
        };
        myFile = tempFile;
        FileIOPermissionAccess tempAccess[] = 
        {
            FileIOPermissionAccess::AllAccess,
                FileIOPermissionAccess::Append,
                FileIOPermissionAccess::NoAccess,
                FileIOPermissionAccess::PathDiscovery,
                FileIOPermissionAccess::Read,
                FileIOPermissionAccess::Write
        };
        myAccess = tempAccess;
        ResetIndex();
    }

public:
    void ResetIndex()
    {
        fileIndex = 0;
    }
    // Create a FileIOPermission using FileIOPermissionAccess that is passed in.
public:
    bool CreateFilePath([Out]FileIOPermission** fileIOPerm, [Out]String** file, FileIOPermissionAccess fpa)
    {

        if(fileIndex == myFile->Length) 
        {
            *fileIOPerm = new FileIOPermission(PermissionState::None);
            *file=S"";
            fileIndex++;
            return true;

        }
        if(fileIndex > myFile->Length) 
        {
            *fileIOPerm = 0;
            *file = S"";
            return false;
        }

        *file = myFile[fileIndex++];

        try
        {
            *fileIOPerm = new FileIOPermission(fpa, *file);
            return true;
        } 
        catch(Exception* e)
        {
            Console::WriteLine(S"Cannot create FileIOPermission: {0} {1}", *file, e);
            *fileIOPerm = new FileIOPermission(PermissionState::None);
            *file=S"";
            return true;
        }
    }
}; // End of FileIOGenerator.

public __gc class FileIOPermissionDemo
{
    // IsSubsetOf determines whether the current permission is a subset of the specified permission.
    // This method compares various FileIOPermission paths with FileIOPermissionAccess set to AllAccess.
private:
    bool IsSubsetOfDemo()
    {

        bool returnValue = true;

        String* fileIO1;
        String* fileIO2;

        FileIOPermission* fileIOPerm1;
        FileIOPermission* fileIOPerm2;


        FileIOGenerator* fileIOGen1 = new FileIOGenerator();
        FileIOGenerator* fileIOGen2 = new FileIOGenerator();

        fileIOGen1->ResetIndex();
        while(fileIOGen1->CreateFilePath(&fileIOPerm1, &fileIO1, FileIOPermissionAccess::AllAccess)) 
        {
            if(fileIOPerm1 == 0) continue;

            Console::WriteLine(S"**********************************************************\n");

            fileIOGen2->ResetIndex();

            while(fileIOGen2->CreateFilePath(&fileIOPerm2, &fileIO2, FileIOPermissionAccess::AllAccess)) 
            {
                String* firstPermission = fileIO1->Equals(S"") | fileIO1->Equals((String*)0) ? S"null" : fileIO1 ;
                String* secondPermission = fileIO2->Equals(S"") | fileIO2->Equals((String*)0) ? S"null" : fileIO2;
                if(fileIOPerm2 == 0) continue;
                try
                {            
                    if (fileIOPerm1->IsSubsetOf(fileIOPerm2))
                    {

                        Console::WriteLine(S"{0} is a subset of {1}\n", firstPermission, secondPermission);
                    }
                    else
                    {
                        Console::WriteLine(S"{0} is not a subset of {1}\n", firstPermission, secondPermission);
                    }

                }
                catch(Exception* e) 
                {
                    Console::WriteLine(S"An exception was thrown for subset :{0}\n{1}\n{2}",
                        (fileIO1->Equals(S"")?S"null":fileIO1), (fileIO2->Equals(S"")?S"null":fileIO2), e);
                }
            }
        }
        return returnValue;
    }
    // Union creates a new permission that is the union of the current permission and the specified permission.
private:
    bool UnionDemo()
    {

        bool returnValue = true;

        String* fileIO1;
        String* fileIO2;

        FileIOPermission* fileIOPerm1;
        FileIOPermission* fileIOPerm2;

        IPermission* fileIOPerm3;

        FileIOGenerator* fileIOGen1 = new FileIOGenerator();
        FileIOGenerator* fileIOGen2 = new FileIOGenerator();

        fileIOGen1->ResetIndex();
        while(fileIOGen1->CreateFilePath(&fileIOPerm1, &fileIO1, FileIOPermissionAccess::Read)) 
        {
            if(fileIO1 == 0) continue;

            Console::WriteLine(S"**********************************************************\n");
            fileIOGen2->ResetIndex();

            while(fileIOGen2->CreateFilePath(&fileIOPerm2, &fileIO2, FileIOPermissionAccess::Read)) 
            {

                try
                {
                    if(fileIOPerm2 == 0) continue;

                    String* firstPermission = fileIO1->Equals(S"") | fileIO1->Equals((String*)0) ? S"null" : fileIO1 ;
                    String* secondPermission = fileIO2->Equals(S"") | fileIO2->Equals((String*)0) ? S"null" : fileIO2;
                    fileIOPerm3 = dynamic_cast<FileIOPermission*>(fileIOPerm1->Union(fileIOPerm2));
                    fileIOPerm3 = fileIOPerm1->Union(fileIOPerm2);

                    if(fileIOPerm3 == 0) 
                    {
                        Console::WriteLine(S"The union of {0}  and {1} is null.", firstPermission, secondPermission);
                    }
                    else
                    {
                        Console::WriteLine(S"The union of {0}  and {1} = \n\t{2}", firstPermission, secondPermission,
                            (dynamic_cast<FileIOPermission*>(fileIOPerm3))->GetPathList(FileIOPermissionAccess::Read)[0]);
                    }
                }
                catch(Exception* e) 
                {
                    Console::WriteLine(S"An exception was thrown for union {0}", e);
                    returnValue=false;
                }

            }

        }

        return returnValue;

    }

    // Intersect creates and returns a new permission that is the intersection of the current 
    // permission and the permission specified.
private:
    bool IntersectDemo()
    {

        bool returnValue = true;

        String* fileIO1;
        String* fileIO2;

        FileIOPermission* fileIOPerm1;
        FileIOPermission* fileIOPerm2;
        FileIOPermission* fileIOPerm3;


        FileIOGenerator* fileIOGen1 = new FileIOGenerator();
        FileIOGenerator* fileIOGen2 = new FileIOGenerator();

        fileIOGen1->ResetIndex();
        while(fileIOGen1->CreateFilePath(&fileIOPerm1, &fileIO1, FileIOPermissionAccess::Read)) 
        {
            if(fileIO1 == 0) continue;
            Console::WriteLine(S"**********************************************************\n");
            fileIOGen2->ResetIndex();

            while(fileIOGen2->CreateFilePath(&fileIOPerm2, &fileIO2, FileIOPermissionAccess::Read)) 
            {
                if(fileIOPerm2 == 0) continue;
                String* firstPermission = fileIO1->Equals(S"") | fileIO1->Equals((String*)0) ? S"null" : fileIO1 ;
                String* secondPermission = fileIO2->Equals(S"") | fileIO2->Equals((String*)0) ? S"null" : fileIO2;
                try
                {

                    fileIOPerm3 = dynamic_cast<FileIOPermission*>(fileIOPerm1->Intersect(fileIOPerm2));
                    if (fileIOPerm3 != 0 && fileIOPerm3->GetPathList(FileIOPermissionAccess::Read) != 0)
                    {

                        Console::WriteLine(S"The intersection of {0}  and \n\t{1} = \n\t{2}", firstPermission, secondPermission,
                            (dynamic_cast<FileIOPermission*>(fileIOPerm3))->GetPathList(FileIOPermissionAccess::Read)[0]);
                    }
                    else
                    {
                        Console::WriteLine(S"The intersection of {0}  and {1} is null.", firstPermission, secondPermission);
                    }
                }
                catch(Exception* e) 
                {
                    Console::WriteLine(S"An exception was thrown for intersection {0}", e);
                    returnValue=false;
                }
            }
        }

        return returnValue;

    }
    //Copy creates and returns an identical copy of the current permission.
private:
    bool CopyDemo()
    {
        bool returnValue = true;
        String* fileIO1;
        FileIOPermission* fileIOPerm1;
        FileIOPermission* fileIOPerm2;

        FileIOGenerator* fileIOGen1 = new FileIOGenerator();
        FileIOGenerator* fileIOGen2 = new FileIOGenerator();

        fileIOGen1->ResetIndex();
        while(fileIOGen1->CreateFilePath(&fileIOPerm1, &fileIO1, FileIOPermissionAccess::Read)) 
        {
            if(fileIO1 == 0 ) continue;  
            Console::WriteLine(S"**********************************************************\n");
            fileIOGen2->ResetIndex();
            try
            {            
                fileIOPerm2 = dynamic_cast<FileIOPermission*>(fileIOPerm1->Copy());
                if (fileIOPerm2 != 0)
                {
                    Console::WriteLine(S"Result of copy = {0}\n", fileIOPerm2);
                }
                else
                {
                    Console::WriteLine(S"Result of copy is null. \n");
                }
            }
            catch(Exception* e) 
            {
                {
                    if (fileIO1->Equals(S""))
                    {
                        Console::WriteLine( S"The target FileIOPermission is empty, copy failed.");

                    }
                    else
                        Console::WriteLine(e);
                }
                continue;
            }
        }
        return returnValue;
    }
    // ToXml creates an XML encoding of the permission and its current state; 
    // FromXml reconstructs a permission with the specified state from the XML encoding. 
private:
    bool ToFromXmlDemo()
    {

        bool returnValue = true;

        String* fileIO1;
        FileIOPermission* fileIOPerm1;
        FileIOPermission* fileIOPerm2;


        FileIOGenerator* fileIOGen1 = new FileIOGenerator();
        FileIOGenerator* fileIOGen2 = new FileIOGenerator();

        fileIOGen1->ResetIndex();
        while(fileIOGen1->CreateFilePath(&fileIOPerm1, &fileIO1, FileIOPermissionAccess::Read)) 
        {
            if(fileIOPerm1 == 0) continue;
            Console::WriteLine(S"********************************************************\n");
            fileIOGen2->ResetIndex();
            try
            {            
                fileIOPerm2= new FileIOPermission(PermissionState::None);
                fileIOPerm2->FromXml(fileIOPerm1->ToXml());
                Console::WriteLine(S"Result of ToFromXml = {0}\n", fileIOPerm2);

            }
            catch(Exception* e) 
            {
                Console::WriteLine(S"ToFromXml failed :{0}{1}", fileIOPerm1, e);
                continue;
            }
        }

        return returnValue;

    }
    // AddPathList adds access for the specified files and directories to the existing state of the permission.
    // SetPathList sets the specified access to the specified files and directories, replacing the existing state 
    // of the permission.
    // GetPathList gets all files and directories that have the specified FileIOPermissionAccess.
private:
    bool SetGetPathListDemo()
    {
        try
        {
            Console::WriteLine(S"********************************************************\n");

            FileIOPermission* fileIOPerm1;
            Console::WriteLine(S"Creating a FileIOPermission with AllAccess rights for 'C:\\Examples\\Test\\TestFile.txt");
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess::AllAccess, S"C:\\Examples\\Test\\TestFile.txt");
            Console::WriteLine(S"Adding 'C:\\Temp' to the write access list, and \n 'C:\\Examples\\Test' to read access.");
            fileIOPerm1->AddPathList(FileIOPermissionAccess::Write, S"C:\\Temp");
            fileIOPerm1->AddPathList(FileIOPermissionAccess::Read, S"C:\\Examples\\Test");
            String* paths[] = fileIOPerm1->GetPathList(FileIOPermissionAccess::Read);
            Console::WriteLine(S"Read access before SetPathList = ");
            IEnumerator* myEnum = paths->GetEnumerator();
            while (myEnum->MoveNext())
            {
                String* path = __try_cast<String*>(myEnum->Current);
                Console::WriteLine(S"\t{0}", path);
            }
            Console::WriteLine(S"Setting the read access list to \n'C:\\Temp'");
            fileIOPerm1->SetPathList(FileIOPermissionAccess::Read, S"C:\\Temp");
            paths = fileIOPerm1->GetPathList(FileIOPermissionAccess::Read);
            Console::WriteLine(S"Read access list after SetPathList = ");
            IEnumerator* myEnum1 = paths->GetEnumerator();
            while (myEnum1->MoveNext())
            {
                String* path = __try_cast<String*>(myEnum1->Current);
                Console::WriteLine(S"\t{0}", path);
            }

            paths = fileIOPerm1->GetPathList(FileIOPermissionAccess::Write);
            Console::WriteLine(S"Write access list after SetPathList = ");
            IEnumerator* myEnum2 = paths->GetEnumerator();
            while (myEnum2->MoveNext())
            {
                String* path = __try_cast<String*>(myEnum2->Current);
                Console::WriteLine(S"\t{0}", path);
            }

            Console::WriteLine(S"Write access = \n{0}", fileIOPerm1->GetPathList(FileIOPermissionAccess::AllAccess));

        }
        catch (ArgumentException* e)
        {
            // FileIOPermissionAccess.AllAccess can not be used as a parameter for GetPathList.
            Console::WriteLine(S"An ArgumentException occurred as a result of using AllAccess. This property cannot be used as a parameter in GetPathList because it represents more than one type of file variable access. : \n{0}", e);
        }

        return true;        
    }
    // The AllFiles property gets or sets the permitted access to all files.
    // The AllLocalFiles property gets or sets the permitted access to all local files.
private:
    bool AllFilesDemo()
    {
        try
        {
            Console::WriteLine(S"********************************************************\n");

            FileIOPermission* fileIOPerm1;
            Console::WriteLine(S"Creating a FileIOPermission and adding read access for all files");
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess::AllAccess, S"C:\\Examples\\Test\\TestFile.txt");
            fileIOPerm1->AllFiles = FileIOPermissionAccess::Read;
            Console::WriteLine(S"AllFiles access = {0}", __box(fileIOPerm1->AllFiles));
            Console::WriteLine(S"Adding AllAccess rights for local files.");
            fileIOPerm1->AllLocalFiles = FileIOPermissionAccess::AllAccess;
            Console::WriteLine(S"AllLocalFiles access = {0}", __box(fileIOPerm1->AllLocalFiles));

        }
        catch (ArgumentException* e)
        {
            Console::WriteLine(e);
            return false;
        }

        return true;        
    }
    // Invoke all demos.
public:
    bool RunDemo()
    {

        bool ret=true;
        bool retTmp;
        // Call the IsSubsetOfPath demo.
        if(retTmp= IsSubsetOfDemo())Console::WriteLine(S"IsSubsetOf demo completed successfully.");
        else Console::WriteLine(S"IsSubsetOf demo failed.");
        ret=retTmp && ret;

        // Call the Union demo.
        if(retTmp= UnionDemo())Console::WriteLine(S"Union demo completed successfully.");
        else Console::WriteLine(S"Union demo failed.");
        ret=retTmp && ret;

        // Call the Intersect demo.    
        if(retTmp= IntersectDemo())Console::WriteLine(S"Intersect demo completed successfully.");
        else Console::WriteLine(S"Intersect demo failed.");
        ret=retTmp && ret;


        // Call the Copy demo.    
        if(retTmp= CopyDemo())Console::WriteLine(S"Copy demo completed successfully.");
        else Console::WriteLine(S"Copy demo failed.");
        ret=retTmp && ret;

        // Call the ToFromXml demo.    
        if(retTmp= ToFromXmlDemo())Console::WriteLine(S"ToFromXml demo completed successfully.");
        else Console::WriteLine(S"ToFromXml demo failed.");
        ret=retTmp && ret;

        // Call the SetGetPathList demo.    
        if(retTmp= SetGetPathListDemo())Console::WriteLine(S"SetGetPathList demo completed successfully.");
        else Console::WriteLine(S"SetGetPathList demo failed.");
        ret=retTmp && ret;

        // Call the AllFiles demo.    
        if(retTmp= AllFilesDemo())Console::WriteLine(S"AllFiles demo completed successfully.");
        else Console::WriteLine(S"AllFiles demo failed.");
        ret=retTmp && ret;

        return (  ret );    

    }
};

// Test harness.
int main() 
{
    try
    {
        FileIOPermissionDemo* democase = new FileIOPermissionDemo();
        bool ret = democase->RunDemo();
        if (ret)
        {
            Console::WriteLine(S"FileIOPermission demo completed successfully.");
            Console::WriteLine(S"Press the Enter key to exit.");
            Console::ReadLine();
            System::Environment::ExitCode = 100;
        }
        else
        {
            Console::WriteLine(S"FileIOPermission demo failed.");
            Console::WriteLine(S"Press the Enter key to exit.");
            Console::ReadLine();
            System::Environment::ExitCode = 101;
        }
    }
    catch(Exception* e)
    {
        Console::WriteLine(S"FileIOPermission demo failed");
        Console::WriteLine(e);
        Console::WriteLine(S"Press the Enter key to exit.");
        Console::ReadLine();
        System::Environment::ExitCode = 101;
    }
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.Security.Permissions

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

FileIOPermission メンバ | System.Security.Permissions 名前空間 | アクセス許可 | アクセス許可の要求 | FileIOPermissionAccess | FileIOPermissionAttribute