Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Запись символов в строку

С помощью приведенного ниже примера кода можно записать определенное количество символов из массива символов в существующую строку, начиная с указанной позиции в этом массиве. Для этого, как показано ниже, используется StringWriter.

Пример

--------

Надежное программирование

Этот пример иллюстрирует использование StringBuilder для изменения существующей строки. Обратите внимание, что это требует дополнительной декларации using, поскольку класс StringBuilder является членом пространства имен System.Text. Вместо того чтобы определять строку и затем преобразовывать ее в массив символов, с помощью примера можно напрямую создать и инициализировать массив символов.

В результате получаются следующие выходные данные.

Some number of characters to

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.

------