Tải bản đầy đủ - 0 (trang)
5-22. Manipulate the Access Control List of a File or Directory

5-22. Manipulate the Access Control List of a File or Directory

Tải bản đầy đủ - 0trang

CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



How It Works

The .NET Framework includes support for ACLs for resources like I/O, registry, and threading classes.

You can retrieve and apply the ACL for a resource by using the GetAccessControl and SetAccessControl

methods defined in the corresponding resource classes. For example, the File and Directory classes

define both these methods, which let you manipulate the ACLs for a file or directory.

To add or remove an ACL-associated right of a file or directory, you need to first retrieve the

FileSecurity or DirectorySecurity object currently applied to the resource using the GetAccessControl

method. Once you retrieve this object, you need to perform the required modification of the rights, and

then apply the ACL back to the resource using the SetAccessControl method. Access rights are updated

using any of the add and remove methods provided in the security class.



The Code

The following example demonstrates the effect of denying Everyone Read access to a temporary file,

using a console application. An attempt to read the file after a change in the ACL triggers a security

exception.

using System;

using System.IO;

using System.Security.AccessControl;

namespace Apress.VisualCSharpRecipes.Chapter05

{

static class Recipe05_22

{

static void Main(string[] args)

{

FileStream stream;

string fileName;

// Create a new file and assign full control to 'Everyone'.

Console.WriteLine("Press any key to write a new file...");

Console.ReadKey(true);

fileName = Path.GetRandomFileName();

using (stream = new FileStream(fileName, FileMode.Create))

{

// Do something.

}

Console.WriteLine("Created a new file " + fileName + ".");

Console.WriteLine();

// Deny 'Everyone' access to the file

Console.WriteLine("Press any key to deny 'Everyone' " +

"access to the file...");

Console.ReadKey(true);

SetRule(fileName, "Everyone",

FileSystemRights.Read, AccessControlType.Deny);



251



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



Console.WriteLine("Removed access rights of 'Everyone'.");

Console.WriteLine();

// Attempt to access file.

Console.WriteLine("Press any key to attempt " +

"access to the file...");

Console.ReadKey(true);

try

{

stream = new FileStream(fileName, FileMode.Create);

}

catch (Exception ex)

{

Console.WriteLine("Exception thrown: ");

Console.WriteLine(ex.ToString());

}

finally

{

stream.Close();

stream.Dispose();

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

static void AddRule(string filePath, string account,

FileSystemRights rights, AccessControlType controlType)

{

// Get a FileSecurity object that represents the

// current security settings.

FileSecurity fSecurity = File.GetAccessControl(filePath);

// Add the FileSystemAccessRule to the security settings.

fSecurity.AddAccessRule(new FileSystemAccessRule(account,

rights, controlType));

// Set the new access settings.

File.SetAccessControl(filePath, fSecurity);

}

static void SetRule(string filePath, string account,

FileSystemRights rights, AccessControlType controlType)

{

// Get a FileSecurity object that represents the

// current security settings.

FileSecurity fSecurity = File.GetAccessControl(filePath);



252



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



// Add the FileSystemAccessRule to the security settings.

fSecurity.ResetAccessRule(new FileSystemAccessRule(account,

rights, controlType));

// Set the new access settings.

File.SetAccessControl(filePath, fSecurity);

}

}

}



5-23. Compress Data

Problem

You need to read or write compressed data.



Solution

Use the System.IO.Compression.GZipStream or System.IO.Compression.DeflateStream to compress or

decompress data.



How It Works

The GZipStream and DeflateStream classes allow you to use the popular ZIP and Deflate compression

algorithms to compress or decompress data. The constructors for both classes accept a System.IO.

Stream instance (which is where data should be written to or read from) and a value from the

CompressionMode enumeration, which allows you to specify that you wish to compress or decompress

data. Both of these classes only read and write bytes and byte arrays—it is often convenient to combine

these classes with streams that are able to read and write other data types, such as in the example for this

recipe.



The Code

The following sample creates a new file and uses the GZipStream class to write compressed data to it from

a StreamWriter instance. The file is closed and then opened in read mode so that the compressed data

can be decompressed and written to the console:

using System;

using System.IO;

using System.IO.Compression;



253



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



namespace Recipe05_23

{

class Recipe05_23

{

static void Main(string[] args)

{

// Create the compression stream.

GZipStream zipout = new GZipStream(

File.OpenWrite("compressed_data.gzip"),

CompressionMode.Compress);

// wrap the gzip stream in a stream writer

StreamWriter writer = new StreamWriter(zipout);

// Write the data to the file.

writer.WriteLine("the quick brown fox");

// Close the streams.

writer.Close();

// Open the same file so we can read the

// data and decompress it.

GZipStream zipin = new GZipStream(

File.OpenRead("compressed_data.gzip"),

CompressionMode.Decompress);

// Wrap the gzip stream in a stream reader.

StreamReader reader = new StreamReader(zipin);

// Read a line from the stream and print it out.

Console.WriteLine(reader.ReadLine());

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



5-24. Log Data to a File

Problem

You need to write data from a collection or an array to a log file.



Solution

Use the static System.IO.File.WriteAllLines method.



254



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



How It Works

The File.WriteAllLines method takes a file name and a collection or array of strings as parameters, and

writes each entry on a separate line in the file specified. You can select which entries in the collection or

array are written by applying a LINQ expression before calling the WriteAllLinesMethod.



The Code

The following example creates a List that contains a number of strings, representing two kinds of

logging data. All of the entries are written to one file, and LINQ is used to query the collection so that

only certain entries are written to a second file. See Chapter 2 for recipes that use LINQ to query

collections.

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.IO;



namespace Recipe05_24

{

class Recipe05_24

{

static void Main(string[] args)

{

// Create a list and populate it.

List myList = new List();

myList.Add("Log entry 1");

myList.Add("Log entry 2");

myList.Add("Log entry 3");

myList.Add("Error entry 1");

myList.Add("Error entry 2");

myList.Add("Error entry 3");

// Write all of the entries to a file.

File.WriteAllLines("all_entries.log", myList);

// Only write out the errors.

File.WriteAllLines("only_errors.log",

myList.Where(e => e.StartsWith("Error")));

}

}

}



255



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

5-22. Manipulate the Access Control List of a File or Directory

Tải bản đầy đủ ngay(0 tr)

×