"Finishing" C # file Operations Encyclopedia (Samwang)
File and folder operations are mainly used in the following categories:
1.File class:
Provides static methods for creating, copying, deleting, moving, and opening files, and assists in creating FileStream objects.
Msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file (v=vs.80). aspx
2.FileInfo class:
Provides instance methods for creating, copying, deleting, moving, and opening files, and helps create FileStream objects
Msdn:http://msdn.microsoft.com/zh-cn/library/system.io.fileinfo (v=vs.80). aspx
3.Directory class:
Exposes static methods that are used to create, move, and enumerate through directories and subdirectories.
Msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directory.aspx
4.DirectoryInfo class:
Exposes instance methods that are used to create, move, and enumerate directories and subdirectories.
Msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx
(Note: The following dirpath indicates the folder path, filepath represents the file path)
1. Create a folder
Directory.CreateDirectory (@ "D:\TestDir");
2. Create a file
Creating a file will cause the file to be accessed so that it cannot be deleted and edited. It is recommended to use the using.
using (File.create (@ "D:\TestDir\TestFile.txt"));
3. deleting files
When deleting a file, it is a good idea to determine if the file exists!
if (file.exists (FilePath)) { file.delete (filePath);}
4. Delete a folder
Deleting a folder requires handling the exception. The specified exception can be captured. MSDN:HTTP://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/62T64DB3 (v=vs.80). aspx
Directory.delete (Dirpath); Delete empty directory, otherwise you need to capture the specified exception handling Directory.delete (Dirpath, true);//delete the directory and all its contents
5. Delete all files and folders in the specified directory
There are generally two ways to do this: 1. After you delete the directory, create an empty directory 2. Find the underlying file and folder path iteration Delete
1//<summary> 2///delete all contents under the specified directory: method One--delete the directory and create an empty directory 3//</summary> 4//< ;p Aram Name= "Dirpath" ></param> 5 public static void Deletedirectorycontentex (String dirpath) 6 { 7 if (directory.exists (Dirpath)) 8 {9 directory.delete (Dirpath); 10 Directory.CreateDirectory (Dirpath);}12}13//<summary>15//Delete all in the specified directory Content: Method Two--Find all files and subfolders deleted from//</summary>17//<param name= "Dirpath" ></param>18 PU Blic static void Deletedirectorycontent (String dirpath) (Directory.Exists (Dirpath)) 21 {$ foreach (string content in Directory.getfilesystementries (Dirpath)) 23 {24 if (content) directory.exists {directory.delete (content, tr UE); 27 }28 Else if (file.exists (content)) {File.delete (CO ntent); 31}32}33}34}
6. Reading files
There are many ways to read files, and the file class already encapsulates four types:
First, directly using the file class
1.public static string ReadAllText (string path);
2.public Static string[] ReadAllLines (string path);
3.public static ienumerable<string> ReadLines (string path);
4.public Static byte[] ReadAllBytes (string path);
The above-obtained content is the same, but the return type is different, according to their own needs to call.
Second, using the stream to read the file
There are StreamReader and FileStream respectively. Please see the code for more information.
1//readalllines 2 Console.WriteLine ("--{0}", "ReadAllLines"); 3 list<string> List = new List<string> (File.ReadAllLines (FilePath)); 4 list. ForEach (str = 5 {6 Console.WriteLine (str); 7}); 8 9//readalltext10 Console.WriteLine ("--{0}", "ReadAllLines"); string filecontent = File.readalltext (FilePath); Console.WriteLine (filecontent);//streamreader15 Console.WriteLine ("--{0}", "StreamReader"); + using (StreamReader sr = new StreamReader (filePath)) 17 {18//method one: reads the stream from the current position of the stream to the end filecontent = string. Empty;20 filecontent = Sr. ReadToEnd (); Console.WriteLine (filecontent); 22//Method Two: A row of rows is read to the NULL23 file Content = string. Empty;24 string strLine = string. empty;25 WHILe (strLine! = null)-StrLine = Sr. ReadLine (); Filecontent + = strline+ "\ r \ n";}30 Console.WriteLine (f Ilecontent); 31}
7. Writing files
Write the file content similar to the read file, please refer to read the file description.
1 //writealllines 2 file.writealllines (filepath,new string[]{"11111", "22222", "3333"}); 3 File.delete ( FilePath); 4 5 //writealltext 6 file.writealltext (FilePath, "11111\r\n22222\r\n3333\r\n"); 7 File.delete ( FilePath); 8 9 //streamwriter10 using (StreamWriter SW = new StreamWriter (FilePath)) one by one { sw. Write ("11111\r\n22222\r\n3333\r\n"), SW. Flush ();
9. File path
Path operations for files and folders are in the path class. In addition, you can use the Environment class, which contains information about the environment and the program.
1 string dirpath = @ "D:\TestDir"; 2 string FilePath = @ "D:\TestDir\TestFile.txt"; 3 Console.WriteLine ("<<<<<<<<<<<{0}>>>>>>>>>>", "File path"); 4//Get current Path 5 Console.WriteLine (environment.currentdirectory); 6//File or folder Directory 7 Console.WriteLine (Path.getdirectoryname (FilePath)); D:\TestDir 8 Console.WriteLine (Path.getdirectoryname (Dirpath)); D:9//File extension Console.WriteLine (path.getextension (FilePath)); . txt11//FileName Console.WriteLine (Path.getfilename (FilePath)); Testfile.txt13 Console.WriteLine (Path.getfilename (Dirpath)); TestDir14 Console.WriteLine (Path.getfilenamewithoutextension (FilePath)); TESTFILE15//absolute path Console.WriteLine (Path.GetFullPath (FilePath)); D:\TestDir\TestFile.txt17 Console.WriteLine (Path.GetFullPath (Dirpath)); D:\TestDir 18//Change extension Console.WriteLine (Path.changeextension (FilePath, ". jpg"));//d:\testdir\ TESTFILE.JPG20//root directory Console.WriteLine (Path.getpathroot (Dirpath)); D:\ 22//Generate Path Console.WriteLine (Path.Combine (New string[] {@ "d:\", "BaseDir", "SubDir", "testfile.t XT "})); D:\BaseDir\SubDir\TestFile.txt24//Generate the folder name or file name Console.WriteLine (Path.getrandomfilename ()); 26 Creates a uniquely named 0-byte temporary file on disk and returns the full path of the file Console.WriteLine (Path.gettempfilename ()); 28//returns the current The path of the system's Temp folder is Console.WriteLine (Path.gettemppath ()); 30//Invalid characters in file name is Console.WriteLine ( Path.getinvalidfilenamechars ()); 32//Invalid character in Path Console.WriteLine (Path.getinvalidpathchars ());
10. File attributes operation
Both the file class and the FileInfo can be implemented. The difference between a static method and an instantiated Method!
1 //use File Class 2 Console.WriteLine (File.getattributes (FilePath)); 3 file.setattributes (FilePath, Fileattributes.hidden | FILEATTRIBUTES.READONLY); 4 Console.WriteLine (File.getattributes (FilePath)); 5 6 //user filinfo Class 7 FileInfo fi = new FileInfo (FilePath); 8 Console.WriteLine (FI. Attributes.tostring ()); 9 fi. Attributes = Fileattributes.hidden | Fileattributes.readonly; Hidden with read-only Console.WriteLine (FI. Attributes.tostring ()); one//read-only with System properties, delete will prompt to deny access to the fi. Attributes = fileattributes.archive;14 Console.WriteLine (FI. Attributes.tostring ());
11. Move all folders and files in a folder to another folder
If you are moving in the same drive letter, call the Directory.move method directly! The cross-drive character uses the following recursive Method!
1//<summary> 2///Move all folders in folder with files to another folder 3//</summary> 4//<param Name= "SourcePath" > source folder </param> 5//<param name= "destpath" > Destination folder </param> 6 public s tatic void MoveFolder (String sourcepath,string destpath) 7 {8 if (directory.exists (SourcePath)) 9 {Ten if (! Directory.Exists (DestPath)) 11 {12//target directory does not exist then create a TRY14 {directory.createdirectory (destpath);}17 CA TCH (Exception ex) ("Create target directory failed:" + ex.) {Exception Message); 20}21}22//Get all files under source file list<string> Files = new list<string> (Directory.GetFiles (SourcePath)); Files. ForEach (c =>25 {DestFile string = Path.Combine (new String[]{destpath,path.getfilename (c)}); 27 Overwrite mode, if (File.exists (destfile)) 29 {30 File.delete (destfile);}32 File.move (c, destfile); 33}); 34 Get all directory files under source file list<string> folders = new List<string> (Directory.getdirectorie S (sourcepath)); folders. ForEach (c =>38 {DestDir string = Path.Combine (new string[] {destpath, PATH.GETF Ilename (c)});//directory.move must be moved in the same root directory to be active and not to move through different volumes. //directory.move (c, DestDir); 42 43//using recursive method to achieve the MoveFolder (c, DestDir); 45}); }47 Else48 {$ throwNew DirectoryNotFoundException ("Source directory does not exist! "); 50} 51}
12. Copy all folders and files in the folder to another folder
If you need to move a file of the specified type or a directory containing some characters, simply add the query criteria to the Directory.GetFiles!
1//<summary> 2///Copy all folders in folder with files to another folder 3//</summary> 4//<param Name= "SourcePath" > source folder </param> 5//<param name= "destpath" > Destination folder </param> 6 public s tatic void CopyFolder (String sourcepath,string destpath) 7 {8 if (directory.exists (SourcePath)) 9 {Ten if (! Directory.Exists (DestPath)) 11 {12//target directory does not exist then create a TRY14 {directory.createdirectory (destpath);}17 CA TCH (Exception ex) ("Create target directory failed:" + ex.) {Exception Message); 20}21}22//Get all files under source file list<string> Files = new list<string> (Directory.GetFiles (SourcePath)); Files. ForEach (c =>25 {DestFile string = Path.Combine (new String[]{destpath,path.getfilename (c)}); 27 File.Copy (c, destfile,true);//Coverage Mode 28}); 29//Get all directory files under source file 30 list<string> folders = new List<string> (directory.getdirectories (SourcePath)); Folders. ForEach (c =>32 {DestDir string = Path.Combine (new string[] {destpath, PATH.GETF Ilename (c)}); 34//Use recursive method to achieve CopyFolder (c, DestDir); 36}); PNs}38 Else39 {$ throw new DirectoryNotFoundException ("Source directory does not exist! "); 41} 42}
"Finishing" C # file Operations Encyclopedia (Samwang)