var dirPath = ZConfig.cacheImagePath; DirectoryInfo directoryInfo = new DirectoryInfo(dirPath); if (!directoryInfo.Exists) { System.IO.Directory.CreateDirectory(dirPath); }
方式2
1 2 3 4 5 6
string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "XHCLASS"); if (!Directory.Exists(savePath)) { System.IO.Directory.CreateDirectory(savePath); }
classWriteAllText { publicstaticasync Task ExampleAsync() { string text = "A class is the most powerful data type in C#. Like a structure, " + "a class defines the data and behavior of the data type. ";
int counter = 0; // Read the file and display it line by line. foreach (string line in System.IO.File.ReadLines(@"c:\test.txt")) { System.Console.WriteLine(line); counter++; } System.Console.WriteLine("There were {0} lines.", counter); // Suspend the screen. System.Console.ReadLine();
privatestaticvoiddeleteFile(string filepath) { new Thread( o => { Thread.Sleep(30000); FileInfo fi = new FileInfo(filepath); if (fi.Exists) { fi.Delete(); } } ).Start(); }
publicclassRecursiveFileSearch { static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
staticvoidMain() { // Start with drives if you have to search the entire computer. string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
// Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. if (!di.IsReady) { Console.WriteLine("The drive {0} could not be read", di.Name); continue; } System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir); }
// Write out all the files that could not be processed. Console.WriteLine("Files with restricted access:"); foreach (string s in log) { Console.WriteLine(s); } // Keep the console window open in debug mode. Console.WriteLine("Press any key"); Console.ReadKey(); }
publicclassStackBasedIteration { staticvoidMain(string[] args) { // Specify the starting folder on the command line, or in // Visual Studio in the Project > Properties > Debug pane. TraverseTree(args[0]);
Console.WriteLine("Press any key"); Console.ReadKey(); }
publicstaticvoidTraverseTree(string root) { // Data structure to hold names of subfolders to be // examined for files. Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root)) { thrownew ArgumentException(); } dirs.Push(root);
string[] files = null; try { files = System.IO.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. foreach (stringfilein files) { try { // Perform whatever action is required in your scenario. System.IO.FileInfo fi = new System.IO.FileInfo(file); Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime); } catch (System.IO.FileNotFoundException e) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. Console.WriteLine(e.Message); continue; } }
// Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach (string str in subDirs){ dirs.Push(str); } } } }
// Simple synchronous file copy operations with no user interface. // To run this sample, first create the following directories and files: // C:\Users\Public\TestFolder // C:\Users\Public\TestFolder\test.txt // C:\Users\Public\TestFolder\SubDir\test.txt publicclassSimpleFileCopy { staticvoidMain() { string fileName = "test.txt"; string sourcePath = @"C:\Users\Public\TestFolder"; string targetPath = @"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths. string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location: // Create a new target folder. // If the directory already exists, this method does not create a new directory. System.IO.Directory.CreateDirectory(targetPath);
// To copy a file to another location and // overwrite the destination file if it already exists. System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory. if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(s, destFile, true); } } else { Console.WriteLine("Source path does not exist!"); }
// Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
移动文件和目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Simple synchronous file move operations with no user interface. publicclassSimpleFileMove { staticvoidMain() { string sourceFile = @"C:\Users\Public\public\test.txt"; string destinationFile = @"C:\Users\Public\private\test.txt";
// To move a file or folder to a new location: System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine // path strings, use the System.IO.Path class. System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private"); } }
// Simple synchronous file deletion operations with no user interface. // To run this sample, create the following files on your drive: // C:\Users\Public\DeleteTest\test1.txt // C:\Users\Public\DeleteTest\test2.txt // C:\Users\Public\DeleteTest\SubDir\test2.txt
publicclassSimpleFileDelete { staticvoidMain() { // Delete a file by using File class static method... if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt")) { // Use a try block to catch IOExceptions, to // handle the case of the file already being // opened by another process. try { System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); return; } }
// ...or by using FileInfo instance method. System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt"); try { fi.Delete(); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); }
// Delete a directory. Must be writable or empty. try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } // Delete a directory and all subdirectories with Directory static method... if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest")) { try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true); }
// ...or with DirectoryInfo instance method. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public"); // Delete this dir and all subdirs. try { di.Delete(true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } }