FileIOPermission-Klasse

Steuert den Zugriff auf Dateien und Ordner. Diese Klasse kann nicht vererbt werden.

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

Diese Berechtigung unterscheidet zwischen den folgenden vier Typen von E/A-Dateizugriff, die durch FileIOPermissionAccess bereitgestellt werden:

  • Read: Lesezugriff auf den Dateiinhalt oder auf Informationen über die Datei, z. B. deren Größe oder den Zeitpunkt der letzten Änderung.

  • Write: Schreibzugriff auf den Inhalt der Datei oder auf Informationen über die Datei, um z. B den Dateinamen ändern zu können. Lässt außerdem Löschen und Überschreiben zu.

  • Append: Nur die Möglichkeit zum Schreiben am Dateiende. Kein Lesezugriff.

  • PathDiscovery: Zugriff auf die Informationen im Pfad selbst. Dies schützt vertrauliche Informationen im Pfad, z. B. Benutzernamen, oder Informationen zur Verzeichnisstruktur, die im Pfad erkennbar sind. Dieser Wert gewährt keinen Zugriff auf Dateien oder Ordner, die durch den Pfad dargestellt werden.

Alle diese Berechtigungen sind von einander unabhängig. Dies bedeutet, dass ein bestimmter Typ von Zugriffsberechtigung keine andere Berechtigung voraussetzt. Eine Write-Berechtigung z. B. setzt keine Read-Berechtigung oder Append-Berechtigung voraus. Wenn mehrere Berechtigungen gewährt werden sollen, können diese mithilfe der bitweisen OR-Operation verknüpft werden, wie im folgenden Codebeispiel gezeigt. Dateiberechtigungen werden in Form von eindeutigen, absoluten Pfaden definiert. Aufrufe sollten immer mit eindeutigen Dateipfaden durchgeführt werden.

FileIOPermission beschreibt geschützte Operationen für Dateien und Ordner. Die File-Klasse bietet sicheren Zugriff auf Dateien und Ordner. Die Sicherheitsüberprüfung des Zugriffs erfolgt bei der Erstellung des Handles für die Datei. Die sich aus der Sicherheitsüberprüfung ergebende Leistungsbeeinträchtigung wird verringert, wenn die Überprüfung zur Erstellungszeit durchgeführt wird. Das Öffnen einer Datei ist ein einmaliger Vorgang, während Lese- und Schreibvorgänge in einer geöffneten Datei mehrmals erfolgen können. Sobald die Datei geöffnet ist, werden keine weiteren Überprüfungen durchgeführt. Das Objekt wird möglicherweise missbraucht, wenn es an einen nicht vertrauenswürdigen Aufrufer übergeben wird. Dateihandles sollten z. B. nicht in öffentlichen globalen statischen Feldern gespeichert werden, in denen Code mit geringeren Berechtigungen auf die Handles zugreifen kann.

FileIOPermissionAccess gibt Aktionen an, die für die Datei oder den Ordner ausgeführt werden können. Darüber hinaus können diese Aktionen mit der bitweisen OR-Operation zu komplexen Instanzen verbunden werden.

Beim Zugriff auf einen Ordner wird ebenfalls der Zugriff auf die darin enthaltenen Dateien sowie auf sämtliche Dateien und Ordner in den untergeordneten Ordnern gewährt. Beispielsweise wird beim Read-Zugriff auf C:\Ordner1\ auch Read-Zugriff auf C:\Ordner1\Datei1.txt, C:\Ordner1\Ordner2\, C:\Ordner1\Ordner2\Datei2.txt usw. gewährt.

VorsichtVorsicht

Unrestricted FileIOPermission gewährt Zugriff auf alle Pfade in einem Dateisystem, einschließlich mehrerer Pfadnamen, über die auf dieselbe Datei zugegriffen wird. Um für den Zugriff auf eine Datei Deny festzulegen, müssen Sie Deny für alle möglichen Pfade der Datei festlegen. Wenn z. B. \\Server\Freigabe dem Netzlaufwerk X zugeordnet ist und Sie Deny für den Zugriff auf \\Server\Freigabe\Datei festlegen möchten, müssen Sie Deny für \\Server\Freigabe\Datei, X:\Datei und alle anderen Pfade festlegen, über die Sie auf die Datei zugreifen können. Ein einfacheres Verfahren für den Umgang mit mehreren Pfaden besteht in der Kombination aus PermitOnly und Deny. Im vorhergehenden Beispiel können Sie PermitOnly für \\Server\Freigabe und Deny für \\Server\Freigabe\Datei festlegen, wodurch alle alternativen Pfade vollständig beseitigt werden. Weitere Informationen über dieses Thema und über die Verwendung von PermitOnly mit Deny finden Sie unter "Kanonisierungsprobleme beim Verwenden von Deny" in Verwenden der Deny-Methode.

HinweisHinweis

Pfade der Form \\Server\Freigabe\Scheinordner\..\Datei werden vom Sicherheitssystem in die kanonische Form \\Server\Freigabe\Datei konvertiert, sodass Sie Deny nur für den kanonischen Pfad \\Server\Freigabe\Datei festlegen müssen. Syntaktische Variationen, mit denen derselbe Pfad angegeben werden kann, können Sie außer Acht lassen. Der Punktoperator (.) kann einfach, mehrfach oder in Verbindung mit nachfolgenden Leerzeichen angezeigt werden. Leerzeichen werden ignoriert, wenn sie dem Punktoperator folgen. Ein einzelner Punkt wie im Pfad C:\temp\test\.\test.txt wird ignoriert, was im Pfad C:\temp\test\test.txt resultiert. Mehrere Punktoperatoren werden als ".." behandelt, d. h., das unmittelbar vorhergehende Verzeichnis wird übersprungen. So wird beispielsweise der Pfad C:\temp\test\.... \test.txt als C:\temp\test.txt interpretiert.

HinweisHinweis

Deny ist unter dem Dateisystem Windows NTFS am effizientesten. NTFS bietet eine deutliche höhere Sicherheit als FAT32. Ausführliche Informationen über NTFS finden Sie in der Windows-Dokumentation.

Die folgenden Beispiele veranschaulichen den von FileIOPermission verwendeten Code. Nach den folgenden beiden Zeilen Code stellt das Objekt f die Berechtigung zum Lesen aller Dateien auf den lokalen Datenträgern des Clientcomputers dar.

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

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

Nach den folgenden beiden Zeilen Code stellt das Objekt f2 die Berechtigung zum Lesen von C:\test_r und zum Lesen und Schreiben in C:\example\out.txt dar. Read und Write stellen die Berechtigungen für Dateien und Ordner wie bereits beschrieben dar.

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");

Im folgenden Beispiel werden viele der FileIOPermission-Member veranschaulicht.

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

Alle öffentlichen statischen (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.

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

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0
Anzeigen: