Tải bản đầy đủ - 0 (trang)
5-18. Use an Isolated Store

5-18. Use an Isolated Store

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

CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



Solution

Use the IsolatedStorageFile and IsolatedStorageFileStream classes from the

System.IO.IsolatedStorage namespace. These classes allow your application to write data to a file in a

user-specific directory without needing permission to access the local hard drive directly.



How It Works

The .NET Framework includes support for isolated storage, which allows you to read and write to a userspecific virtual file system that the Common Language Runtime (CLR) manages. When you create

isolated storage files, the data is automatically serialized to a unique location in the user profile path

(typically a path like C:\Documents and Settings\[username]\Local Settings\Application

Data\isolated storage\[guid_identifier]).

One reason you might use isolated storage is to give a partially trusted application limited ability to

store data. For example, the default CLR security policy gives local code unrestricted FileIOPermission,

which allows it to open or write to any file. Code that you run from a remote server on the local intranet

is automatically assigned fewer permissions. It lacks the FileIOPermission, but it has the

IsolatedStoragePermission, giving it the ability to use isolated stores. (The security policy also limits the

maximum amount of space that can be used in an isolated store.) Another reason you might use an

isolated store is to better secure data. For example, data in one user’s isolated store will be restricted

from another nonadministrative user.

By default, each isolated store is segregated by user and assembly. That means that when the same

user runs the same application, the application will access the data in the same isolated store. However,

you can choose to segregate it further by application domain so that multiple AppDomain instances

running in the same application receive different isolated stores.

The files are stored as part of a user’s profile, so users can access their isolated storage files on any

workstation they log onto if roaming profiles are configured on your local area network. (In this case, the

store must be specifically designated as a roaming store by applying the IsolatedStorageFile.Roaming

flag when it’s created.) By letting the .NET Framework and the CLR provide these levels of isolation, you

can relinquish responsibility for maintaining the separation between files, and you do not need to worry

that programming oversights or misunderstandings will cause loss of critical data.



The Code

The following example shows how you can access isolated storage:

using System;

using System.IO;

using System.IO.IsolatedStorage;

namespace Apress.VisualCSharpRecipes.Chapter05

{

static class Recipe05_18

{

static void Main(string[] args)

{

// Create the store for the current user.

using (IsolatedStorageFile store =



244



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



IsolatedStorageFile.GetUserStoreForAssembly())

{

// Create a folder in the root of the isolated store.

store.CreateDirectory("MyFolder");

// Create a file in the isolated store.

using (Stream fs = new IsolatedStorageFileStream(

"MyFile.txt", FileMode.Create, store))

{

StreamWriter w = new StreamWriter(fs);

// You can now write to the file as normal.

w.WriteLine("Test");

w.Flush();

}

Console.WriteLine("Current size: " +

store.UsedSize.ToString());

Console.WriteLine("Scope: " + store.Scope.ToString());

Console.WriteLine("Contained files include:");

string[] files = store.GetFileNames("*.*");

foreach (string file in files)

{

Console.WriteLine(file);

}

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

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

Console.ReadLine();

}

}

}

The following demonstrates using multiple AppDomain instances running in the same application to

receive different isolated stores:

// Access isolated storage for the current user and assembly

// (which is equivalent to the first example).

store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |

IsolatedStorageScope.Assembly, null, null);

// Access isolated storage for the current user, assembly,

// and application domain. In other words, this data is

// accessible only by the current AppDomain instance.

store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |

IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain,

null, null);



245



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



5-19. Monitor the File System for Changes

Problem

You need to react when a file system change is detected in a specific path (such as a file modification or

creation).



Solution

Use the System.IO.FileSystemWatcher component, specify the path or file you want to monitor, and

handle the Created, Deleted, Renamed, and Changed events.



How It Works

When linking together multiple applications and business processes, it’s often necessary to create a

program that waits idly and becomes active only when a new file is received or changed. You can create

this type of program by scanning a directory periodically, but you face a key trade-off. The more often

you scan, the more system resources you waste. The less often you scan, the longer it will take to detect a

change. The solution is to use the FileSystemWatcher class to react directly to Windows file events.

To use FileSystemWatcher, you must create an instance and set the following properties:





Path indicates the directory you want to monitor.







Filter indicates the types of files you are monitoring.







NotifyFilter indicates the type of changes you are monitoring.



FileSystemWatcher raises four key events: Created, Deleted, Renamed, and Changed. All of these events

provide information through their FileSystemEventArgs parameter, including the name of the file (Name),

the full path (FullPath), and the type of change (ChangeType). The Renamed event provides a

RenamedEventArgs instance, which derives from FileSystemEventArgs, and adds information about the

original file name (OldName and OldFullPath). If you need to, you can disable these events by setting the

FileSystemWatcher.EnableRaisingEvents property to false. The Created, Deleted, and Renamed events

are easy to handle. However, if you want to use the Changed event, you need to use the NotifyFilter

property to indicate the types of changes you want to watch. Otherwise, your program might be

swamped by an unceasing series of events as files are modified.

The NotifyFilter property can be set using any combination of the following values from the

System.IO.NotifyFilters enumeration:





Attributes







CreationTime







DirectoryName







FileName







LastAccess



246



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O







LastWrite







Security







Size



The Code

The following example shows a console application that handles Created and Deleted events, and tests

these events by creating a test file:

using System;

using System.IO;

using System.Windows.Forms;

namespace Apress.VisualCSharpRecipes.Chapter05

{

static class Recipe05_19

{

static void Main()

{

// Configure the FileSystemWatcher.

using (FileSystemWatcher watch = new FileSystemWatcher())

{

watch.Path = Application.StartupPath;

watch.Filter = "*.*";

watch.IncludeSubdirectories = true;

// Attach the event handler.

watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);

watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);

watch.EnableRaisingEvents = true;

Console.WriteLine("Press Enter to create a file.");

Console.ReadLine();

if (File.Exists("test.bin"))

{

File.Delete("test.bin");

}

// Create test.bin.

using (FileStream fs = new FileStream("test.bin", FileMode.Create))

{

// Do something.

}

Console.WriteLine("Press Enter to terminate the application.");

Console.ReadLine();

}



247



www.it-ebooks.info



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

5-18. Use an Isolated Store

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

×