Export (0) Print
Expand All

FileIOPermission Class

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

Namespace: System.Security.Permissions
Assembly: mscorlib (in mscorlib.dll)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public sealed class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class FileIOPermission extends CodeAccessPermission implements IUnrestrictedPermission
SerializableAttribute 
ComVisibleAttribute(true) 
public final class FileIOPermission extends CodeAccessPermission implements IUnrestrictedPermission

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 noteCaution

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 Using the Deny Method.

NoteNote

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. The dot operator (.) can appear singly, in multiples, or in combination with trailing blank characters. Blanks are ignored when following the dot operator. A single dot, such as in the address C:\temp\test\.\test.txt is ignored, resulting in an address of C:\temp\test\test.txt. Multiple dot operators are treated as a "..", meaning the immediately preceding directory is skipped. For example, the address C:\temp\test\.... \test.txt results in the path C:\temp\test.txt.

NoteNote

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.

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.

FileIOPermission f = new FileIOPermission(PermissionState.None);
f.AllLocalFiles = FileIOPermissionAccess.Read;

FileIOPermission f = new FileIOPermission(PermissionState.None);
f.set_AllLocalFiles(FileIOPermissionAccess.Read);

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.

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

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

The following example demonstrates many of the FileIOPermission members.

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 fileIO1 ))
        {
            if(fileIO1 == "")
                fileIOPerm1 = new FileIOPermission(PermissionState.None);
            else
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileIO1);

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

            fileIOGen2.ResetIndex();

            while (fileIOGen2.CreateFilePath(out fileIO2))
            {
                if (fileIO2 == "")
                    fileIOPerm2 = new FileIOPermission(PermissionState.None);
                else
                    fileIOPerm2 = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileIO2);
                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 fileIO1 ))
        {
            if (fileIO1 == "")
                fileIOPerm1 = new FileIOPermission(PermissionState.None);
            else
            fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO1);
            if (fileIO1 == null) continue;

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

            while (fileIOGen2.CreateFilePath( out fileIO2 ))
            {
                if (fileIO2 == "")
                    fileIOPerm2 = new FileIOPermission(PermissionState.None);
                else
                    fileIOPerm2 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO2);
                try
                {
                    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 fileIO1 ))
        {
            if (fileIO1 == "")
                fileIOPerm1 = new FileIOPermission(PermissionState.None);
            else
                fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO1);

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

            while (fileIOGen2.CreateFilePath( out fileIO2 ))
            {
                if (fileIO2 == "")
                    fileIOPerm2 = new FileIOPermission(PermissionState.None);
                else
                    fileIOPerm2 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO2);
                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 fileIO1 ))
        {
            if (fileIO1 == "")
                fileIOPerm1 = new FileIOPermission(PermissionState.None);
            else
                fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO1);

            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 fileIO1 ))
        {
            if (fileIO1 == "")
                fileIOPerm1 = new FileIOPermission(PermissionState.None);
            else
                fileIOPerm1 = new FileIOPermission(FileIOPermissionAccess.Read, fileIO1);

            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  file path string.
    public bool CreateFilePath( out string file )
    {

        if (fileIndex == myFile.Length)
        {

            file = "";
            fileIndex++;
            return true;

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

        file = myFile[fileIndex++];

        try
        {
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Cannot create FileIOPermission: " + file + " " + e);
            file = "";
            return true;
        }
    }
}

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

import System.*;
import System.Security.*;
import System.Security.Permissions.*;
import 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 boolean IsSubsetOfDemo() 
    {
        boolean returnValue = true;
        String fileIO1[] = new String[1] ;
        String fileIO2[] = new String[1] ;
        FileIOPermission fileIOPerm1[] = new FileIOPermission[1] ;
        FileIOPermission fileIOPerm2[] = new FileIOPermission[1] ;
        
        FileIOGenerator fileIOGen1 =  new FileIOGenerator();
        FileIOGenerator fileIOGen2 =  new FileIOGenerator();
        
        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, 
            FileIOPermissionAccess.AllAccess)) {
            if (fileIOPerm1[0] == null) {
                continue ;
            }         
            Console.WriteLine("***********************" 
                + "***********************************\n");
            fileIOGen2.ResetIndex();
            
            while(fileIOGen2.CreateFilePath(fileIOPerm2, fileIO2, 
                FileIOPermissionAccess.AllAccess)) {
                String firstPermission = (fileIO1[0].equals("") == 
                    true | fileIO1[0] == null) ? "null" : fileIO1[0];
                String secondPermission = (fileIO2[0].equals("") == 
                    true | fileIO2[0] == null) ? "null" : fileIO2[0];
                if (fileIOPerm2[0] == null) {
                    continue ;
                }
                try {
                    if (fileIOPerm1[0].IsSubsetOf(fileIOPerm2[0])) {
                        Console.WriteLine((firstPermission 
                            + " is a subset of " 
                            + secondPermission + "\n"));
                    }
                    else {
                        Console.WriteLine((firstPermission 
                            + " is not a subset of " 
                            + secondPermission + "\n"));
                    }
                } 
                catch(System.Exception e) {
                    Console.WriteLine(("An exception was thrown for subset :" 
                        + ((fileIO1[0].equals("") == true) ? 
                        "null" : (fileIO1[0] + "\n" 
                        + ((fileIO2[0].equals("") == true) ? 
                        "null" : fileIO2[0]) + "\n" + e))));
                }
            }
        }
        return returnValue ;
    } //IsSubsetOfDemo   

    // Union creates a new permission that is the union of the current 
    // permission and the specified permission.
    private boolean UnionDemo() 
    {
        boolean returnValue = true;
        String fileIO1[] = new String[1];
        String fileIO2[] = new String[1];
        FileIOPermission fileIOPerm1[] = new FileIOPermission[1];
        FileIOPermission fileIOPerm2[] = new FileIOPermission[1];
        
        IPermission fileIOPerm3;
        
        FileIOGenerator fileIOGen1 =  new FileIOGenerator();
        FileIOGenerator fileIOGen2 =  new FileIOGenerator();
        
        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(fileIOPerm1, 
            fileIO1, FileIOPermissionAccess.Read)) {
            if (fileIO1[0] == null) {
                continue ;
            }
            Console.WriteLine("*****************************" 
                + "*****************************\n");
            fileIOGen2.ResetIndex();
            
            while(fileIOGen2.CreateFilePath(fileIOPerm2, 
                fileIO2, FileIOPermissionAccess.Read)) {
                try {
                    if (fileIOPerm2[0] == null) {
                        continue ;
                    }
                    
                    String firstPermission = (fileIO1[0].equals("")==
                        true | fileIO1[0] == null) ? "null" : fileIO1[0];
                    String secondPermission = (fileIO2[0].equals("") == 
                        true | fileIO2[0] == null) ? "null" : fileIO2[0];
                    fileIOPerm3 =((FileIOPermission)(fileIOPerm1[0].
                        Union(fileIOPerm2[0])));
                    fileIOPerm3 = fileIOPerm1[0].Union(fileIOPerm2[0]);
                    
                    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).
                            get_Item( 0)));
                    }
                }
                catch(System.Exception e) {
                    Console.WriteLine(("An exception was " 
                        + "thrown for union " + e));
                    returnValue = false;
                }
            }
        }
        return returnValue ;
    } //UnionDemo    

    // Intersect creates and returns a new permission that is 
    // the intersection of the current
    // permission and the permission specified.
    private boolean IntersectDemo() 
    {
        boolean returnValue = true;
        String fileIO1[] = new String[1];
        String fileIO2[] = new String[1];
        FileIOPermission fileIOPerm1[] = new FileIOPermission[1];
        FileIOPermission fileIOPerm2[] = new FileIOPermission[1];
        FileIOPermission fileIOPerm3;
        
        FileIOGenerator fileIOGen1 =  new FileIOGenerator();
        FileIOGenerator fileIOGen2 =  new FileIOGenerator();
        
        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, 
            FileIOPermissionAccess.Read)) {
            if (fileIO1[0] == null) {
                continue ;
            }
            Console.WriteLine("***************************" 
                + "*******************************\n");
            fileIOGen2.ResetIndex();
            
            while(fileIOGen2.CreateFilePath(fileIOPerm2, fileIO2, 
                FileIOPermissionAccess.Read)) {
                if ( fileIOPerm2[0] == null  ) {
                    continue ;
                }
                String firstPermission = (fileIO1[0].equals("") == 
                    true | fileIO1[0] == null) ? "null" : fileIO1[0];
                String secondPermission = (fileIO2[0].equals("") == 
                    true | fileIO2[0] == null) ? "null" : fileIO2[0];
                try {
                    fileIOPerm3 =((FileIOPermission)(fileIOPerm1[0].
                    Intersect(fileIOPerm2[0])));
                    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).
                            get_Item( 0)));
                    }
                    else {
                        Console.WriteLine(("The intersection of " 
                            + firstPermission + " and " 
                            + secondPermission + " is null."));
                    }
                }
                catch(System.Exception e) {
                    Console.WriteLine(("An exception was " 
                        + "thrown for intersection " + e));
                        returnValue = false;
                }
            }
        }
        return returnValue ;
    } //IntersectDemo    

    //Copy creates and returns an identical copy of the current permission.
    private boolean CopyDemo() 
    {
        boolean returnValue = true;
        String fileIO1[] = new String[1];
        FileIOPermission fileIOPerm1[] = new FileIOPermission[1];
        FileIOPermission fileIOPerm2[] = new FileIOPermission[1];
        FileIOGenerator fileIOGen1 =  new FileIOGenerator();
        FileIOGenerator fileIOGen2 =  new FileIOGenerator();
        
        fileIOGen1.ResetIndex();
        while(fileIOGen1.CreateFilePath(fileIOPerm1, fileIO1, 
            FileIOPermissionAccess.Read)) {
                if (fileIO1 == null) {
                    continue ;
                }
                Console.WriteLine("**********************************" 
                + "************************\n");
                fileIOGen2.ResetIndex();
                try {
                    fileIOPerm2[0] =((FileIOPermission)(fileIOPerm1[0].Copy()));
                    if (fileIOPerm2[0]  != null) {
                        Console.WriteLine(("Result of copy = " 
                        + fileIOPerm2[0].ToString() + "\n"));
                    }
                    else {
                        Console.WriteLine("Result of copy is null. \n");
                    }
                }
                catch(System.Exception e) {
                    if (fileIO1[0].Equals("")) {
                        Console.WriteLine("The target FileIOPermission " 
                            + "is empty, copy failed.");
                    }
                    else {
                        Console.WriteLine(e);
                    }
                }
                continue ;
            }
        return returnValue ;
    } //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 boolean ToFromXmlDemo() 
    {
        boolean returnValue = true;
        String fileIO1[] = new String[1];
        FileIOPermission fileIOPerm1[] = new FileIOPermission[1];
        FileIOPermission fileIOPerm2[] = new FileIOPermission[1];

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

    // AllAccess
    // 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 boolean 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 = ");
            for (int iCtr = 0; iCtr < paths.length; iCtr++) {
                String path = paths[iCtr];
                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 = ");
            for (int iCtr = 0; iCtr < paths.length; iCtr++) {
                String path = paths[iCtr];
                Console.WriteLine(("\t" + path));
            }            
            
            paths = fileIOPerm1.GetPathList(FileIOPermissionAccess.Write);
            Console.WriteLine("Write access list after SetPathList = ");
            for (int iCtr = 0; iCtr < paths.length; iCtr++) {
                String path = paths[iCtr];
                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 ;
    } //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 boolean 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.set_AllFiles ( FileIOPermissionAccess.Read);
            Console.WriteLine(("AllFiles access = " 
                + fileIOPerm1.get_AllFiles()));
            Console.WriteLine("Adding AllAccess rights for local files.");
            fileIOPerm1.set_AllLocalFiles (FileIOPermissionAccess.AllAccess);
            Console.WriteLine(("AllLocalFiles access = " 
                + fileIOPerm1.get_AllLocalFiles()));
        } 
        catch(ArgumentException e) {
            Console.WriteLine(e);
            return false ;
        }
        return true ;
    } //AllFilesDemo

    // Invoke all demos.
    public boolean RunDemo() 
    {
        boolean ret = true;
        boolean retTmp;
        // Call the IsSubsetOfPath demo.
        if (retTmp = IsSubsetOfDemo()) {
            Console.get_Out().WriteLine("IsSubsetOf demo completed " 
                + "successfully.");
        }
        else {
            Console.get_Out().WriteLine("IsSubsetOf demo failed.");
        }
        ret = retTmp && ret;
        
        // Call the Union demo.
        if (retTmp = UnionDemo()) {
            Console.get_Out().WriteLine("Union demo completed successfully.");
        }
        else {
            Console.get_Out().WriteLine("Union demo failed.");
        }
        ret = retTmp && ret;
        // Call the Intersect demo.
        if (retTmp = IntersectDemo()) {
            Console.get_Out().WriteLine("Intersect demo completed " 
                + "successfully.");
        }
        else {
            Console.get_Out().WriteLine("Intersect demo failed.");
        }
        ret = retTmp && ret;
        
        // Call the Copy demo.
        if (retTmp = CopyDemo()) {
            Console.get_Out().WriteLine("Copy demo completed successfully.");
        }
        else {
            Console.get_Out().WriteLine("Copy demo failed.");
        }
        ret = retTmp && ret;
        
        // Call the ToFromXml demo.
        if (retTmp = ToFromXmlDemo()) {
            Console.get_Out().WriteLine("ToFromXml demo completed " 
                + "successfully.");
        }
        else {
            Console.get_Out().WriteLine("ToFromXml demo failed.");
        }
        ret = retTmp && ret;
        
        // Call the SetGetPathList demo.
        if (retTmp = SetGetPathListDemo()) {
            Console.get_Out().WriteLine("SetGetPathList demo completed " 
                + "successfully.");
        }
        else {
            Console.get_Out().WriteLine("SetGetPathList demo failed.");
        }
        ret = retTmp && ret;
        
        // Call the AllFiles demo.
        if (retTmp = AllFilesDemo()) {
            Console.get_Out().WriteLine("AllFiles demo completed " 
                + "successfully.");
        }
        else {
            Console.get_Out().WriteLine("AllFiles demo failed.");
        }
        ret = retTmp && ret;      
        return ret ;
    } //RunDemo

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

// This class generates FileIOPermission objects.
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();
    } //FileIOGenerator

    public void ResetIndex() 
    {
        fileIndex = 0;
    } //ResetIndex   

    // Create a FileIOPermission using FileIOPermissionAccess 
    // that is passed in.
    public boolean CreateFilePath(FileIOPermission fileIOPerm[], String file[], 
        FileIOPermissionAccess fpa) 
    {
        if (fileIndex == myFile.length) {
            fileIOPerm[0] = new FileIOPermission(PermissionState.None);

            file[0] = "";
            fileIndex++;
            return true ;
        }
        if (fileIndex > myFile.length) {
            fileIOPerm[0] = null;
            file[0] = "";
            return false ;
        }
        file[0] = myFile[fileIndex++];
        
        try {
            fileIOPerm[0] = new FileIOPermission(fpa, file[0]);
            return true ;
        }
        catch(System.Exception e) {
            Console.WriteLine(("Cannot create FileIOPermission: " 
                + file[0] + " " + e));
            fileIOPerm[0] = new FileIOPermission(PermissionState.None);
            file[0] = "";
            return true ;
        }
    } //CreateFilePath
} //FileIOGenerator 

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

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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft