查找现有的文件和目录
您还可以使用独立存储文件来搜索现有的目录和文件。请记住,在存储区中,文件名和目录名是相对于虚文件系统的根目录指定的。此外,Windows 文件系统中的文件和目录名不区分大小写。
要搜索某个目录,请使用 IsolatedStorageFile 的 GetDirectoryNames 实例方法。GetDirectoryNames 采用表示搜索模式的字符串。支持使用单字符 (?) 和多字符 (*) 通配符。这些通配符不能出现在名称的路径部分。也就是说,directory1/*ect* 是有效的搜索字符串,而 *ect*/directory2 不是有效的搜索字符串。
要搜索某个文件,请使用 IsolatedStorageFile 的 GetFileNames 实例方法。对应用于 GetDirectoryNames 的搜索字符串中通配符的相同限制也适用于 GetFileNames。
GetDirectoryNames 和 GetFileNames 都不是递归的,即 IsolatedStorageFile 不提供用于列出存储区中所有目录或文件的方法。但是,下面的代码中部分是递归方法的示例。另外还要注意,GetDirectoryNames 和 GetFileNames 只返回找到的项的目录名或文件名。例如,如果找到目录 RootDir/SubDir/SubSubDir 的匹配项,结果数组中将返回 SubSubDir。
FindingExistingFilesAndDirectories 示例
下面的代码示例阐释如何在独立存储区创建文件和目录。首先,检索一个按用户、域和程序集隔离的存储区并放入 isoStore 变量。CreateDirectory 方法用于设置几个不同的目录,IsolatedStorageFileStream 方法在这些目录中创建一些文件。然后,代码依次通过 GetAllDirectories 方法的结果。该方法使用 GetDirectoryNames 来查找当前目录中的所有目录名。这些名称存储在数组中,然后 GetAllDirectories 调用其本身,传入它所找到的每个目录。结果是在数组中返回的所有目录名。然后,代码调用 GetAllFiles 方法。该方法调用 GetAllDirectories 以查找所有目录的名称,然后它检查每个目录以查找使用 GetFileNames 方法的文件。结果返回到数组中用于显示。
[C#]
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections;
public class FindingExistingFilesAndDirectories{
// Retrieves an array of all directories in the store, and
// displays the results.
public static void Main(){
// This part of the code sets up a few directories and files in the
// store.
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
isoStore.CreateDirectory("TopLevelDirectory");
isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
new IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", FileMode.Create, isoStore);
// End of setup.
Console.WriteLine('\r');
Console.WriteLine("Here is a list of all directories in this isolated store:");
foreach(string directory in GetAllDirectories("*", isoStore)){
Console.WriteLine(directory);
}
Console.WriteLine('\r');
// Retrieve all the files in the directory by calling the GetFiles
// method.
Console.WriteLine("Here is a list of all the files in this isolated store:");
foreach(string file in GetAllFiles("*", isoStore)){
Console.WriteLine(file);
}
}// End of Main.
// Method to retrieve all directories, recursively, within a store.
public static string[] GetAllDirectories(string pattern, IsolatedStorageFile storeFile){
// Get the root of the search string.
string root = Path.GetDirectoryName(pattern);
if (root != "") root += "/";
// Retrieve directories.
string[] directories;
directories = storeFile.GetDirectoryNames(pattern);
ArrayList directoryList = new ArrayList(directories);
// Retrieve subdirectories of matches.
for (int i = 0, max = directories.Length; i < max; i++){
string directory = directoryList[i] + "/";
string[] more = GetAllDirectories (root + directory + "*", storeFile);
// For each subdirectory found, add in the base path.
for (int j = 0; j < more.Length; j++)
more[j] = directory + more[j];
// Insert the subdirectories into the list and
// update the counter and upper bound.
directoryList.InsertRange(i+1, more);
i += more.Length;
max += more.Length;
}
return (string[])directoryList.ToArray(Type.GetType("System.String"));
}
public static string[] GetAllFiles(string pattern, IsolatedStorageFile storeFile){
// Get the root and file portions of the search string.
string fileString = Path.GetFileName(pattern);
string[] files;
files = storeFile.GetFileNames(pattern);
ArrayList fileList = new ArrayList(files);
// Loop through the subdirectories, collect matches,
// and make separators consistent.
foreach(string directory in GetAllDirectories( "*", storeFile))
foreach(string file in storeFile.GetFileNames(directory + "/" + fileString))
fileList.Add((directory + "/" + file));
return (string[])fileList.ToArray(Type.GetType("System.String"));
}// End of GetFiles.
}
读取和写入文件
使用 IsolatedStorageFileStream 类,有多种方法可以打开存储区中的文件。一旦获得了 IsolatedStorageFileStream 之后,可使用它来获取 StreamReader 或 StreamWriter。使用 StreamReader 和 StreamWriter,您可以像对任何其他文件一样读取和写入存储区中的文件。
ReadingAndWritingToFiles 示例
下面的代码示例获得独立存储区,创建一个名为 TestStore.txt 的文件并将“Hello Isolated Storage”写入文件。然后,代码读取该文件并将结果输出到控制台。
[C#]
using System;
using System.IO;
using System.IO.IsolatedStorage;
public class ReadingAndWritingToFiles{
public static int Main(){
// Get an isolated store for this assembly and put it into an
// IsolatedStoreFile object.
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
// This code checks to see if the file already exists.
string[] fileNames = isoStore.GetFileNames("TestStore.txt");
foreach (string file in fileNames){
if(file == "TestStore.txt"){
Console.WriteLine("The file already exists!");
Console.WriteLine("Type \"StoreAdm /REMOVE\" at the command line to delete all Isolated Storage for this user.");
// Exit the program.
return 0;
}
}
writeToFile(isoStore);
Console.WriteLine("The file \"TestStore.txt\" contains:");
// Call the readFromFile and write the returned string to the
//console.
Console.WriteLine(readFromFile(isoStore));
// Exit the program.
return 0;
}// End of main.
// This method writes "Hello Isolated Storage" to the file.
private static void writeToFile(IsolatedStorageFile isoStore){
// Declare a new StreamWriter.
StreamWriter writer = null;
// Assign the writer to the store and the file TestStore.
writer = new StreamWriter(new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew,isoStore));
// Have the writer write "Hello Isolated Storage" to the store.
writer.WriteLine("Hello Isolated Storage");
writer.Close();
Console.WriteLine("You have written to the file.");
}// End of writeToFile.
// This method reads the first line in the "TestStore.txt" file.
public static String readFromFile(IsolatedStorageFile isoStore){
// This code opens the TestStore.txt file and reads the string.
StreamReader reader = new StreamReader(new IsolatedStorageFileStream("TestStore.txt", FileMode.Open,isoStore));
// Read a line from the file and add it to sb.
String sb = reader.ReadLine();
// Close the reader.
reader.Close();
// Return the string.
return sb.ToString();
}// End of readFromFile.
}
删除文件和目录
您可以删除独立存储文件中的目录和文件。请记住,在存储区中,文件名和目录名是与操作系统相关的(在 Microsoft Windows 系统中通常不区分大小写),并且是根据虚文件系统的根目录具体而定的。
IsolatedStoreFile 类提供了两种删除目录和文件的实例方法:DeleteDirectory 和 DeleteFile。如果尝试删除并不存在的文件和目录,则会引发 IsolatedStorageFileException。如果名称中包含有通配符,则 DeleteDirectory 会引发 IsolatedStorageFileException,而 DeleteFile 将引发 ArgumentException。
如果目录中包含任何文件或子目录,DeleteDirectory 将会失败。在 DeletingFilesAndDirectories 示例的一部分中定义了一个方法,该方法删除目录中的所有内容,然后删除目录本身。同样,您可以自己定义一个接受通配符的 DeleteFiles 方法,该方法可以这样来实现:使用 GetFileNames 方法获取所有匹配文件的列表,然后依次删除每个文件。
DeletingFilesAndDirectories 示例
下面的代码示例先创建若干个目录和文件,然后将它们删除。
[C#]
using System;
using System.IO.IsolatedStorage;
using System.IO;
public class DeletingFilesDirectories{
public static void Main(){
// Get a new isolated store for this user domain and assembly.
// Put the store into an isolatedStorageFile object.
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
Console.WriteLine("Creating Directories:");
// This code creates several different directories.
isoStore.CreateDirectory("TopLevelDirectory");
Console.WriteLine("TopLevelDirectory");
isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
Console.WriteLine("TopLevelDirectory/SecondLevel");
// This code creates two new directories, one inside the other.
isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory");
Console.WriteLine();
// This code creates a few files and places them in the directories.
Console.WriteLine("Creating Files:");
// This file is placed in the root.
IsolatedStorageFileStream isoStream1 = new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
Console.WriteLine("InTheRoot.txt");
isoStream1.Close();
// This file is placed in the InsideDirectory.
IsolatedStorageFileStream isoStream2 = new IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", FileMode.Create, isoStore);
Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
Console.WriteLine();
isoStream2.Close();
Console.WriteLine("Deleting File:");
// This code deletes the HereIAm.txt file.
isoStore.DeleteFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
Console.WriteLine();
Console.WriteLine("Deleting Directory:");
// This code deletes the InsideDirectory.
isoStore.DeleteDirectory("AnotherTopLevelDirectory/InsideDirectory/");
Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/");
Console.WriteLine();
}// End of main.
}
总结
上面是VS.NET中.NET中IO的基本概念、示例代码以及访问文件系统的基础方法和流程,大家可以多多实践。有任何建议请MAIL我 paulni@citiz.net。