How to: Add or Remove Access Control List Entries 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Add or Remove Access Control List Entries



To add or remove Access Control List (ACL) entries to or from a file, the FileSecurity or DirectorySecurity object must be obtained from the file or directory, modified, and then applied back to the file or directory.

To add or remove an ACL entry from a File

1. Call the GetAccessControl method to get a FileSecurity object that contains the current ACL entries of a file.

2. Add or remove ACL entries from the FileSecurity object returned from step 1.

3. Pass the FileSecurity object to the SetAccessControl method to apply the changes.

To add or remove an ACL entry from a Directory

1. Call the GetAccessControl method to get a DirectorySecurity object that contains the current ACL entries of a directory.

2. Add or remove ACL entries from the DirectorySecurity object returned from step 1.

3. Pass the DirectorySecurity object to the SetAccessControl method to apply the changes.

 


Добавление или удаление записей списка управления доступом

Чтобы добавить или удалить элементы списка управления доступом (ACL) из файла, необходимо получить объект FileSecurity или объект DirectorySecurity из файла или каталога, изменить его и затем сохранить изменения в файле или каталоге.

Чтобы добавить или удалить элемент списка управления доступом из файла

1. Вызовите метод GetAccessControl для получения объекта FileSecurity, содержащего текущие элементы ACL файла.

2. Добавьте или удалите элементы списка управления доступом из объекта FileSecurity, возвращенного на шаге 1.

3. Передайте объект FileSecurity методу SetAccessControl, чтобы сохранить изменения.

Чтобы добавить или удалить элемент ACL из каталога

1. Вызовите метод GetAccessControl для получения объекта DirectorySecurity, содержащего текущие элементы ACL каталога.

2. Добавьте или удалите элементы списка управления доступом из объекта DirectorySecurity, возвращенного на шаге 1.

3. Передайте объект DirectorySecurity методу SetAccessControl, чтобы сохранить изменения.

 


Example

using System; using System.IO; using System.Security.AccessControl;   namespace FileSystemExample { class FileExample { public static void Main() { try { string fileName = "test.xml";   Console.WriteLine("Adding access control entry for " + fileName);   // Add the access control entry to the file. AddFileSecurity(fileName, @"DomainName\AccountName", FileSystemRights.ReadData, AccessControlType.Allow);   Console.WriteLine("Removing access control entry from " + fileName);   // Remove the access control entry from the file. RemoveFileSecurity(fileName, @"DomainName\AccountName", FileSystemRights.ReadData, AccessControlType.Allow);   Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } }  

 


Пример

ß------


 

// Adds an ACL entry on the specified file for the specified account. public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) {     // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName);   // Add the FileSystemAccessRule to the security settings. fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));   // Set the new access settings. File.SetAccessControl(fileName, fSecurity);   }   // Removes an ACL entry on the specified file for the specified account. public static void RemoveFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) {   // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName);   // Add the FileSystemAccessRule to the security settings. fSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType));   // Set the new access settings. File.SetAccessControl(fileName, fSecurity);   } } }  

Compiling the Code

You must supply a valid user or group account to run this example. This example uses a File object; however, the same procedure is used for the FileInfo, Directory, and DirectoryInfo classes.


 

 

ß------

 

 

Компиляция кода

Чтобы запустить этот пример, необходимо предоставить подходящую учетную запись пользователя или группы. В этом примере используется объект File; однако та же самая процедура используется для классов FileInfo, Directory и DirectoryInfo.

 


How to: Compress Files

Use the GZipStream class to compress and decompress data. The following code example creates a file (test.txt) in the current directory, fills it with text, and displays the contents of the file to the console. The code then uses the GZipStream class to create a compressed version of the file (test.txt.gz) and compares the size of the two files. Finally, the code reads in the compressed file, decompresses it, and writes out a new file (test.txt.gz.txt) to the current directory. The code then displays the contents of the decompressed file.

You can also use the DeflateStream class to compress and decompress data.

Example

using System; using System.Collections.Generic; using System.IO; using System.IO.Compression;   public class CompressionSnippet { public static void Main() { string path = "test.txt";   // Create the text file if it doesn't already exist. if (!File.Exists(path)) { Console.WriteLine("Creating a new test.txt file"); string[] text = new string[] {"This is a test text file.", "This file will be compressed and written to the disk.", "Once the file is written, it can be decompressed", "using various compression tools.", "The GZipStream and DeflateStream class use the same", "compression algorithms, the primary difference is that", "the GZipStream class includes a cyclic redundancy check", "that can be useful for detecting data corruption.", "One other side note: both the GZipStream and DeflateStream", "classes operate on streams as opposed to file-based", "compression; data is read on a byte-by-byte basis, so it", "is not possible to perform multiple passes to determine the", "best compression method. Already compressed data can actually", "increase in size if compressed with these classes."};   File.WriteAllLines(path, text); }

 


Сжатие файлов

Используйте класс GZipStream для сжатия и распаковки данных. Следующий пример кода создает файл (test.txt) в текущем каталоге, заполняет его текстом и выводит содержимое файла на консоль. Затем в коде используется класс GZipStream для создания сжатой версии файла (test.txt.gz) и сравнивается размер двух файлов. В заключение в коде выполняется считывание данных из сжатого файла, его распаковка и запись нового файла (test.txt.gz.txt) в текущий каталог. Затем выводится содержимое распакованного файла.

Также можно использовать класс DeflateStream для сжатия и распаковки данных.

Пример

ß---------


 

Console.WriteLine("Contents of {0}", path);

Console.WriteLine(File.ReadAllText(path));

CompressFile(path);

Console.WriteLine();

UncompressFile(path + ".gz");

Console.WriteLine();

Console.WriteLine("Contents of {0}", path + ".gz.txt");

Console.WriteLine(File.ReadAllText(path + ".gz.txt"));

}

public static void CompressFile(string path)

{

FileStream sourceFile = File.OpenRead(path);

FileStream destinationFile = File.Create(path + ".gz");

byte[] buffer = new byte[sourceFile.Length];

sourceFile.Read(buffer, 0, buffer.Length);

using (GZipStream output = new GZipStream(destinationFile,

CompressionMode.Compress))

{

Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,

destinationFile.Name, false);

output.Write(buffer, 0, buffer.Length);

}

// Close the files.

sourceFile.Close();

destinationFile.Close();

}

 

public static void UncompressFile(string path)

{

FileStream sourceFile = File.OpenRead(path);

FileStream destinationFile = File.Create(path + ".txt");

 

// Because the uncompressed size of the file is unknown,

// we are using an arbitrary buffer size.

byte[] buffer = new byte[4096];

int n;

 

using (GZipStream input = new GZipStream(sourceFile,

CompressionMode.Decompress, false))

{

Console.WriteLine("Decompressing {0} to {1}.", sourceFile.Name,

destinationFile.Name);

 

n = input.Read(buffer, 0, buffer.Length);

destinationFile.Write(buffer, 0, n);

}

 

// Close the files.

sourceFile.Close();

destinationFile.Close();

}

}


 

ß------


Composing Streams

A backing store is a storage medium, such as a disk or memory. Each different backing store implements its own stream as an implementation of the Stream class. Each stream type reads and writes bytes from and to its given backing store. Streams that connect to backing stores are called base streams. Base streams have constructors that have the parameters necessary to connect the stream to the backing store. For example, FileStream has constructors that specify a path parameter, which specifies how the file will be shared by processes, and so on.

The design of the System.IO classes provides simplified stream composing. Base streams can be attached to one or more pass-through streams that provide the functionality you want. A reader or writer can be attached to the end of the chain so that the preferred types can be read or written easily.

The following code example creates a FileStream around the existing MyFile.txt in order to buffer MyFile.txt. (Note that FileStreams are buffered by default.) Next, a StreamReader is created to read characters from the FileStream, which is passed to the StreamReader as its constructor argument. ReadLine reads until Peek finds no more characters.

using System; using System.IO; public class CompBuf { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist!", FILE_NAME); return; } FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); // Create an instance of StreamReader that can read // characters from the FileStream. StreamReader sr = new StreamReader(fsIn); // While not at the end of the file, read lines from the file. while (sr.Peek()>-1) { String input = sr.ReadLine(); Console.WriteLine (input); } sr.Close(); } }

Составление потоков

Резервное хранилище — это устройство хранения информации, например диск или память. В каждом из резервных хранилищ используется собственный поток как реализация класса Stream. Каждый тип потока считывает и записывает байты в собственное резервное хранилище. Потоки, которые связаны с резервными хранилищами, называются базовыми. В конструкторах базовых потоков есть параметры, необходимые для присоединения потока к резервному хранилищу. Например, FileStream имеет конструктор, задающий путь, который определяет порядок совместного использования файла процессами и т. д.

Структура классов System.IO предоставляет упрощенное составление потоков. Базовые потоки могут быть присоединены к одному или нескольким сквозным потокам, которые обеспечивают требуемую функциональность. Модуль чтения или записи может быть присоединен к концу цепочки, что обеспечит легкое считывание или запись предпочитаемых типов.

В следующем примере кода создается поток FileStream для существующего файла MyFile.txt с целью буферизации файла MyFile.txt. (Обратите внимание, что экземпляры класса FileStreams буферизуются по умолчанию.) Затем создается StreamReader для чтения знаков из FileStream, который передается в StreamReader в качестве аргумента его конструктора. Метод ReadLine считывает до тех пор, пока Peek не находит более символов.

ß--------


The following code example creates a FileStream around the existing MyFile.txt in order to buffer MyFile.txt. (Note that FileStreams are buffered by default.) Next, a BinaryReader is created to read bytes from the FileStream, which is passed to the BinaryReader as its constructor argument. ReadByte reads until PeekChar finds no more bytes.

using System; using System.IO; public class ReadBuf { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist.", FILE_NAME); return; } FileStream f = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); // Create an instance of BinaryReader that can // read bytes from the FileStream. BinaryReader sr = new BinaryReader(f); // While not at the end of the file, read lines from the file. while (sr.PeekChar()>-1) { byte input = sr.ReadByte(); Console.WriteLine (input); } sr.Close(); } }

 


В следующем примере кода создается поток FileStream для существующего файла MyFile.txt с целью буферизации файла MyFile.txt. (Обратите внимание, что экземпляры класса FileStreams буферизуются по умолчанию.) Затем создается BinaryReader для чтения байтов из FileStream, который передается в BinaryReader в качестве аргумента его конструктора. Метод ReadByte считывает до тех пор, пока PeekChar не находит более байт.

ß-------


Creating a Writer

The following code example creates a writer, which is a class that can take data of some type and convert it to a byte array that can be passed to a stream.

using System; using System.IO; public class MyWriter { private Stream s; public MyWriter(Stream stream) { s = stream; } public void WriteDouble(double myData) { byte[] b = BitConverter.GetBytes(myData); // GetBytes is a binary representation of a double data type. s.Write(b, 0, b.Length); } public void Close() { s.Close(); } }

In this example, you create a class that has a constructor with a stream argument. From here, you can expose whatever Write methods are necessary. You must convert whatever you are writing to a byte[]. After you obtain the byte[],the Write method writes it to the stream s.

 


Создание класса Writer

В следующем примере создается модуль записи, который представляет собой класс, преобразующий данные одного типа в массив байтов, который затем можно передать в поток.

using System; using System.IO; public class MyWriter { private Stream s; public MyWriter(Stream stream) { s = stream; } public void WriteDouble(double myData) { byte[] b = BitConverter.GetBytes(myData); // GetBytes is a binary representation of a double data type. s.Write(b, 0, b.Length); } public void Close() { s.Close(); } }

В этом примере создается класс с конструктором, аргументом которого является поток. Поэтому есть возможность в дальнейшем обращаться к любым необходимым методам Write. Необходимо преобразовать данные, предназначенные для записи, в массив byte[]. После получения массива byte[] метод Write записывает его в поток s.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 125; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 52.14.8.34 (0.037 с.)