Use .NET IO (5)

zhaozj2021-02-17  60

Find existing files and directories

You can also use independent storage files to search for existing directories and files. Keep in mind that in the storage area, the file name and directory name are specified relative to the root directory of the virtual file system. In addition, files and directory names in the Windows file system are not case sensitive.

To search for a directory, use the ISOLATORAGEFILE method method for the getDirectoryNames instance. GetDirectoryNames uses a string representing the search mode. Supports using single characters (?) And multi-character (*) wildcard. These wildcards cannot appear in the path portion of the name. That is, Directory1 / * ECT * is a valid search string, and * ECT * / Directory2 is not a valid search string.

To search for a file, use the getFileNames instance method for IsolatedStorageFile. The same restrictions for wildcards in search strings for GetDirectoryNames are also applicable to getFileNames.

GetDirectoryNames and getFileNames are not recursive, namely ISOLATedStorageFile does not provide methods for listing all directories or files in the storage area. However, the part of the following code is an example of a recursive method. Also note that getDirectoryNames and getFileNames return only the directory name or file name of the item found. For example, if you find a matching item of the directory rootdir / subdir / subSubdir, SubsubDir will be returned in the result array.

FindingexistingFileSAndDirectories example

The following code example illustrates how to create files and directories in standalone storage area. First, retrieve a memory area isolated by the user, domain, and program, and put it in the isostore variable. The CreateDirectory method is used to set several different directories, and the ISOLATEDSTORAGESTREAM method creates some files in these directories. Then, the code sequentially passes the result of the GetAllDirectories method. This method uses GetDirectoryNames to find all directory names in the current directory. These names are stored in an array, then GetAllDirectories call it itself, incoming each directory it finds. The result is all directory names returned in the array. Then, the code calls the getFiles method. This method calls getAllDirectories to find the name of all directories, then check each directory to find files with the GetFileNames 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 {

// 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) {{g gos

Console.writeline (file);

}

} // end of main.

// Method to Retrieve All Directories, Recursively, the Withnin 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

String Directory = DirectoryList [i] "/";

String [] more = getAllDirectories (root directory "*", storefile;

// for Each Subdirectory Found, Add in the base path.

For (int J = 0; j

// Insert the subdirector 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.

}

Read and write files

With the ISOLATORAGEFISTREAM class, there are a variety of ways to open files in the storage area. Once IsolatedStorageFileStream is obtained, it can be used to get streamreader or streamwriter. With StreamReader and StreamWriter, you can read and write files in the storage area like any other file.

ReadingAnDwritingTofiles example

The following code example obtains a stand-alone memory area, creates a file called TestStore.txt and writes "Hello Isolated Storage" into the file. The code then reads the file and outputs the result to the console.

[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.us.AssEMBLY, NULL, NULL); // this code checks to see letter 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 return string to the

// console.

Console.writeLine (ReadFromfile (isostore);

// exit the program.

Return 0;

} // end of main.

// this Method Writes "Hello isolated" 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 ISOLATEDSTORAGEFISTREAM ("TestStore.txt", FileMode.createNew, isostore);

// Have The Writer Write "Hello isolated Storage" to the store.

Writer.writeline ("Hello isolated");

Writer.close ();

"" 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 ("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.

}

Delete files and directories

You can delete directorys and files in the standalone storage file. Keep in mind that in the storage area, the file name and directory name are related to the operating system (usually in the Microsoft Windows system), and is specifically dependent on 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 the files and directories that do not exist, IsolatedStorageFileException will be triggered. If the name contains a wildcard, DELETEDIRECTORY will trigger IsolatedStorageFileException, while DeleteFile will trigger ArgumentException.

If the directory contains any files or subdirectories, DeletedIRectory will fail. A method is defined in a part of the DELETINGFileSAndDirectories example, which deletes all the contents in the directory and then deletes the directory itself. Similarly, you can define a deletefiles method that accepts wildcards, which can be implemented in this way: use the getFileNames method to get a list of all matching files and then delete each file.

DELETINGFILSASADDIRECTORIES example

The following code example first creates several directory and files, then deletes them.

[C #]

Using system;

Using system.io.IsolatedStorage;

Using system.io;

Public class deledingfilesdirectories {

Public static void main () {

// Get a new isolated store for this user domain and askEMBLY.

// 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 the.

Console.writeline ("CREANG 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 insidedomIRectory.

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.

}

to sum up

The above is the basic concepts, sample code, and the basic methods and processes of IO in VS.NET. Everyone can practice. If you have any suggestions, please Mil I Paulni@citiz.net.

转载请注明原文地址:https://www.9cbs.com/read-28556.html

New Post(0)