Export (0) Print
Expand All

FileIOPermission Class

Controls the ability to access files and folders. This class cannot be inherited.

For a list of all members of this type, see FileIOPermission Members.

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

[Visual Basic]
<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

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

This permission distinguishes between the following four types of file IO access provided by FileIOPermissionAccess:

  • Read: Read access to the contents of the file or access to information about the file, such as its length or last modification time.
  • Write: Write access to the contents of the file or access to change information about the file, such as its name. Also allows for deletion and overwriting.
  • Append: Ability to write to the end of a file only. No ability to read.
  • PathDiscovery: Access to the information in the path itself. This helps protect sensitive information in the path, such as user names, as well as information about the directory structure revealed in the path. This value does not grant access to files or folders represented by the path.

All these permissions are independent, meaning that rights to one do not imply rights to another. For example, Write permission does not imply permission to Read or Append. If more than one permission is desired, they can be combined using a bitwise OR as shown in the code example that follows. File permission is defined in terms of canonical absolute paths; calls should always be made with canonical file paths.

FileIOPermission describes protected operations on files and folders. The File class helps provide secure access to files and folders. The security access check is performed when the handle to the file is created. By doing the check at creation time, the performance impact of the security check is minimized. Opening a file happens once, while reading and writing can happen multiple times. Once the file is opened, no further checks are done. If the object is passed to an untrusted caller, it can be misused. For example, file handles should not be stored in public global statics where code with less permission can access them.

FileIOPermissionAccess specifies actions that can be performed on the file or folder. In addition, these actions can be combined using a bitwise OR to form complex instances.

Access to a folder implies access to all the files it contains, as well as access to all the files and folders in its subfolders. For example, Read access to C:\folder1\ implies Read access to C:\folder1\file1.txt, C:\folder1\folder2\, C:\folder1\folder2\file2.txt, and so on.

CAUTION    Unrestricted FileIOPermission grants permission for all paths within a file system, including multiple pathnames that can be used to access a single given file. To Deny access to a file, you must Deny all possible paths to the file. For example, if \\server\share is mapped to the network drive X, to Deny access to \\server\share\file, you must Deny\\server\share\file, X:\file and any other path that you can use to access the file. A better technique to deal with multiple paths is to use a combination of PermitOnly and Deny. In the above example you can PermitOnly\\server\share, then Deny\\server\share\file, eliminating alternate paths completely. For more information on this subject and the use of PermitOnly with Deny, see Canonicalization Problems Using Deny in the Deny topic.
Note   Paths of the form \\server\share\bogusfolder\..\file are converted into the canonical form \\server\share\file by the security system so you only need to Deny the canonical path, \\server\share\file, and do not need to account for the syntactical variations that can be used to specify the same path.
Note    Deny is most effective when used with the Windows NTFS file system. NTFS offers substantially more security than FAT32. For details on NTFS, see the Windows documentation.

Example

[Visual Basic, C#, C++] The following examples illustrate code that uses FileIOPermission. After the following two lines of code, the object f represents permission to read all files on the client computer's local disks.

[Visual Basic] 
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++] After the following two lines of code, the object f2 represents permissions to read C:\test_r and read and write to C:\example\out.txt. Read and Write represent the file/folder permissions as previously described.

[Visual Basic] 
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++] The following example demonstrates many of the FileIOPermission members.

[Visual Basic] 
' 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] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Security.Permissions

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

FileIOPermission Members | System.Security.Permissions Namespace | Permissions | Requesting Permissions | FileIOPermissionAccess | FileIOPermissionAttribute

Show:
© 2014 Microsoft