Use. NET IO (5) Paul

Source: Internet
Author: User
Tags foreach exit command line contains file system instance method valid root directory

Find existing files and directories


You can also use isolated storage files to search for existing directories and files. Keep in mind that in the store, the file name and directory name are specified relative to the root of the virtual file system. In addition, file and directory names in the Windows file system are case-insensitive.
To search for a directory, use the IsolatedStorageFile GetDirectoryNames instance method. GetDirectoryNamesTakes a string that represents the search pattern. Supports the use of given (?) and multiple character (*) wildcard characters. These wildcard characters cannot appear in the path part of the name. In other words, directory1/*ect* is a valid search string, and *ect*/directory2 is not a valid search string.
To search for a file, use the IsolatedStorageFileGetFileNames instance method. Corresponds to GetDirectoryNamesThe same restrictions for wildcard characters in the search string are also applicable to the GetFileNames
GetDirectoryNamesAnd GetFileNamesare not recursive, that is, IsolatedStorageFileDoes not provide a way to list all directories or files in the store. However, the following code is part of an example of a recursive method. In addition, it should be noted that GetDirectoryNamesAnd GetFileNamesReturns only the directory name or file name of the item found. For example, if a match is found for the directory Rootdir/subdir/subsubdir, Subsubdir is returned in the resulting array.

Findingexistingfilesanddirectories sample


The following code example illustrates how to create files and directories in isolated storage. First, retrieve a store isolated by user, domain, and assembly and put the Isostore variable. CreateDirectorymethod is used to set up several different directories. IsolatedStorageFileStreammethod to create some files in these directories. The code then passes the result of the GetAllDirectories method in turn. This method uses GetDirectoryNamesTo find all directory names in the current directory. These names are stored in an array, and then getalldirectories calls itself, passing in each directory it finds. The result is all the directory names returned in the array. The code then calls the Getallfiles method. The method calls GetAllDirectories to find the name of all directories, and then it checks each directory to find the use of the GetFileNamesThe file for the method. The result is returned to the array for display.
[C #]
Using System;
Using System.IO;
Using System.IO.IsolatedStorage;
Using System.Collections;
public class findingexistingfilesanddirectories{
Displays the results.
public static void Main () {
This section 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's a list of all directories at this isolated store:");
foreach (String directory in GetAllDirectories ("*", Isostore)) {
Console.WriteLine (directory);
}
Console.WriteLine (' \ R ');
Method.
Console.WriteLine ("Here's a list of all", "This isolated store:");
foreach (String file in Getallfiles ("*", Isostore)) {
Console.WriteLine (file);
}
}//end of Main.
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];
Update the counter and upper bound.
Directorylist.insertrange (i+1, more);
i + +. Length;
Max + +. 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);
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.
}

Reading and writing files


With the IsolatedStorageFileStream class, there are several ways to open files in a store. Once you get the IsolatedStorageFileStreamYou can then use it to get StreamReader or StreamWriter. Use StreamReaderAnd StreamWriter, you can read and write to files in the store as you would any other file.

Readingandwritingtofiles sample


The following code example obtains a standalone store, creates a file named TestStore.txt, and writes "Hello Isolated Storage" to the file. The code then reads the file and prints the results to the console.
[C #]
Using System;
Using System.IO;
Using System.IO.IsolatedStorage;
public class readingandwritingtofiles{
public static int Main () {
Get a isolated store for this Assembly
IsolatedStoreFile object.
IsolatedStorageFile Isostore = Isolatedstoragefile.getstore (Isolatedstoragescope.user | isolatedstoragescope.assembly, NULL, NULL);
This code checks to the 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 is 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.
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 "TestStore.txt" file.
public static String ReadFromFile (IsolatedStorageFile isostore) {
This code opens the TestStore.txt file and reads the string.
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.
}

deleting files and directories


You can delete directories and files in isolated storage files. Keep in mind that in the store, the file name and directory name are related to the operating system (typically case-insensitive in a Microsoft Windows system) and are specific to the root directory of the virtual file system.
The IsolatedStoreFile class provides two instance methods for deleting directories and files: DeleteDirectory and DeleteFile. If you try to delete files and directories that do not exist, a isolatedstoragefileexception is raised. If the name contains a wildcard character, the DeleteDirectoryis raised isolatedstoragefileexception, and DeleteFile will cause ArgumentException.
If the directory contains any files or subdirectories, DeleteDirectoryWill fail. In part of the deletingfilesanddirectories example, a method is defined that deletes all content in the directory and then deletes the directory itself. In the same way, you can define your own one that accepts wildcard characters. Deletefilesmethod, which can be implemented in this way: using the GetFileNamesMethod gets a list of all matching files, and then deletes each file in turn.

Deletingfilesanddirectories sample


The following code example creates several directories and files, and then deletes them.
[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 ();
Console.WriteLine ("Deleting Directory:");
This code deletes the insidedirectory.
Isostore. DeleteDirectory ("anothertopleveldirectory/insidedirectory/");
Console.WriteLine ("anothertopleveldirectory/insidedirectory/");
Console.WriteLine ();
}//end of Main.
}

Summarize


Above is the basic concept of IO in vs.net, sample code, and the basic methods and processes to access the file system, and you can do a lot of practice. Have any suggestions please mail me paulni@citiz.net (paulni@citiz.net).


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.