C # obtain the file size, creation time, file information, and attributes of the fileinfo class.

Source: Internet
Author: User
Tags array to string
C # obtain the file size, creation time, file information, and attributes of the fileinfo class. Table 09:00:40 | category: C # | report | font size subscription openfiledialog1 = new openfiledig1 (); if (openfiledialog1.showdialog () = dialogresult. OK) {openfiledialog1.filename; system. io. fileinfo file = new system. io. fileinfo (openfiledialog1.filename); file. name; // file name. length. tostring (); // size ", file. lastaccesstime. tostring (); // The last access time file. lastwritetime. tostring (); // The last modification time fil E. directoryname; // path} The fileinfo class is a sealed class that can be used to create, copy, delete, move, and open files. The fileinfo class has six attributes that can be used to obtain the file name and complete path. For details, see Table 21.9. Table 21.9 attributes of the fileinfo class table description Description Directory obtains the parent directory exists specifies whether the current file exists directoryname obtains the full path length of the file to get the size of the current file (in bytes) isreadonly obtains or sets whether the current file is a read-only name to obtain the file name. The fileinfo and directoryinfo classes share the same attributes inherited by the filesysteminfo class, which are not described in detail here. In addition to the preceding attributes, the fileinfo class also includes instance methods. For details, see table 21.10. Table 21.10 fileinfo class instance method table method description Description create () Create File openread () Open File Delete () in read-only mode Delete () delete specified file openwrite () open the file moveTo () in the write-only mode and move the specified file to the new location. createtext () creates a streamwritercopyto () to copy the existing file to the new file opentext () open the specified text file, and prepare to read content from the file Replace () use the content of another file to replace the content of the specified file appendtext () to create a streamwriter, it can be used to Append content to a text file to open the file. The create (), delete (), moveTo (), copyto (), and replace () methods are used to operate the file, they can be used to create, delete, move, copy, and replace objects in sequence. 21.3.3 you can use the CREATE () method of the file class or the CREATE () method of the fileinfo class to create a file. [Example 21-18] use the CREATE () method of the fileinfo class to create a file named "My. ini. 1. fileinfo Fi = new fileinfo ("My. ini "); 2. fi. create (); analysis: This example first creates the instance fi of the fileinfo class, which is specified as my. INI file, and then call the CREATE () method to create the file. The newly created my. the INI file is stored in the application directory 21.3.4. There are multiple ways to write the specified content to the file, such as the file openwrite () method and fileinfo openwrite () method () method. [Example 21-19] use the openwrite () method of the fileinfo class to "this is a configuration file. "The string is written to a file named my. ini. The specific steps are as follows: (1) Create an instance fi for the fileinfo class, which is specified as the my. ini file. (2) Use the openwrite () method to open the my. ini file and save it as an instance fsw of the filestream class. (3) set the content to be written ("this is a configuration file. "String), and convert it to a byte array, and save it as dataw. (4) Call the write () method of the FSW instance to write the content in the dataw array to the my. ini file. (5) Call the close () method of the FSW instance to close the FSW instance. 1. fileinfo Fi = new fileinfo ("My. ini "); 2. /// create a fileinfo class instance Fi 3. filestream FSW = Fi. openwrite (); 4. /// use openwrite () to open my. INI File 5. string valuew = "this is a configuration file. "; 6. /// set the content to be written. 7. byte [] dataw = system. text. encoding. unicode. getbytes (valuew); 8. /// convert to a byte array and save it as dataw 9. FSW. write (dataw, 0, dataw. length); 10. /// write the content in the dataw array to my. INI file 11. FSW. close (); 12. /// call the close () method of the FSW instance to disable FSW instance analysis: After the preceding sample code is run, "This is a configuration file. "String is written to the file named my. ini. View the content of the my. ini file in notepad, as shown in Figure 21.2. Mainly: My. the content of the INI file has been encoded in Unicode mode. Therefore, you cannot see the actual content of the file 21.3.5. There are multiple methods to read the file. You can read the content from the specified file, for example, the openread () method of the file class and the openread () method of the fileinfo class. [Example 21-20] use the openread () method of the fileinfo class to read the content from the my. ini file and convert it to a string (saved as valuer). Finally, the content of valuer is displayed on the console. The procedure is as follows: (1) create a fileinfo class instance Fi, which is specified as the my. ini file. (2) Open the my. ini file using the openread () method and save it as the FSR instance of the filestream class. (3) create a DATAR array to save the content read from the my. ini file. (4) Call the read () method of the FSW instance to read the content of the my. ini file and save it to the DATAR array. (5) convert the DATAR array into a string and save it as valuer. (6) The value of valuer is displayed. (7) Call the close () method of the FSW instance to close the FSW instance. 1. fileinfo Fi = new fileinfo ("My. ini "); 2. /// create a fileinfo class instance Fi 3. filestream FSR = Fi. openread (); 4. /// use openread () to open my. INI File 5. byte [] DATAR = new byte [(INT) FSR. length]; 6. /// create a DATAR array and save it from my. INI File Read content 7. FSR. read (DATAR, 0, (INT) FSR. length); 8. /// read my. the content of the INI file is saved to the DATAR array 9. string valuer = system. text. encoding. unicode. getstring (DATAR); 10. /// convert the DATAR array to string and save it as valuer 11. console. writeline (V Aluer); 12. /// display my. INI File Content 13. FSR. close (); 14. /// call the close () method of the FSW instance to disable FSW instance analysis: after the sample code is run, "This is a configuration file. "String. 21.3.6 you can use either of the following two methods to move a file. The move () method of the file class: Move the specified file to a new location. [Example 21-21] use the move () method of the file class to move the my. ini file to the my01.ini file. 1. file. move (@ "My. ini "," my01.ini "); analysis: After the code is executed, a new file named my01.ini is created and my. INI file. The moveTo () method of the fileinfo class: Move the specified file to a new location. [Example 21-22] Create an instance fi (indicating the "My. ini" file) of the fileinfo class and call the moveTo () method to move the my. ini file to the my01.ini file. 1. fileinfo Fi = new fileinfo ("My. ini "); 2. fi. moveTo ("my01.ini"); analysis: After the code is executed, a new file named my01.ini is created and my. INI file. 21.3.7 you can use either of the following two methods to delete a file. The Delete () method of the file class: deletes the specified file. [Example 21-23] use the delete () method of the file class to delete the my. ini file. 1. file. Delete (@ "My. ini", "my01.ini"); Delete () method of the fileinfo class: Delete the specified file. [Example 21-24] Create an instance fi (indicating the my. ini file) of the fileinfo class and call the delete () method to delete the my. ini file. 1. fileinfo Fi = new fileinfo ("My. ini "); 2. fi. delete ("My. ini "); 21.4 instance: Read the content of the specified type of files in the directory [instance 21-1] to read the content of all files in the specified directory, specified file type, the read content is displayed on the console. The specific implementation steps are as follows: (1) Open Visual Studio 2008 integrated development environment and create a console application named "sample_21. The application version is. NET Framework 3.5. (2) Right-click program in solution manager. CS node, open the name "program. CS "class file, and add the readerfile (string path) method program code in this file. The readerfile (string path) method reads the content of the specified file (specified by the path parameter) and returns the read content. The procedure is as follows: ① create a filedata variable of the string type to save the read content. ② Read the file content in the try statement. ③ Create a streamreader instance reader that reads the file content, and specify the encoding method of the instance as the default encoding method of the operating system. ④ Call the readtoend () method to read all the content of the file from the beginning to the end and save it as a filedata variable. ⑤ Close the reader instance. ⑥ If an exception occurs in the try statement, an exception is thrown in the catch statement. Based on the above, the program code of the readerfile (string path) method is as follows. 1. //< summary> Read the file content </Summary> 2. public static string readerfile (string path) 3. {4. string filedata = string. empty; 5. try 6. {// read the file content 7. streamreader reader = new 8. streamreader (path, encoding. default); 9. filedata = reader. readtoend (); 10. reader. close (); 11 .} 12. catch (Ti/on ex) {Throw new exceptI 13. /On (ex. message, ex);} // throw an exception 14. return filedata; 15 .} (3) In program. add read to the CS File Code of the ersubdirectory (string path, string filter, ref stringbuilder content) method. This method reads the content of all files in the specified directory (specified by the path parameter) that meet the filter (specified by the filter parameter, the read content is saved to the content parameter (this parameter is a reference parameter. The procedure is as follows: ① determine whether the path parameter is valid. If it is invalid, the method is aborted. ② Create the instance parentdi of the directory information. ③ Use the foreach statement and getfiles () method to search for all files in the specified directory of the parentdi instance that meet the filter (specified by the filter parameter. ④ If the foreach statement finds the file, it reads the content of each file in sequence and saves it to the content parameter. Based on the above, the program code of the readersubdirectory (string path, string filter, ref stringbuilder content) method is as follows: 1. /// <summary> read the content of all objects in the subdirectory </Summary> 2. private Static void readersubdirectory (string path, string filter, ref 3. stringbuilder content) 4. {// determine whether the directory is correct. 5. if (string. isnullorempty (PATH) = true) return; 6. /// create an instance of directory information 7. directoryinfo parentdi = new directoryinfo (PATH); 8. /// read the contents of the specified file in the current directory and Its subdirectories. save to con 10 In the tent variable. foreach (fileinfo fi in parentdi. 11. getfiles (filter, searchopti/on. alldirectories) 12. {13. content. appendline (); 14. content. append (readerfile (Fi. fullname); 15. content. appendline (); 16 .} 17 .} (4) In program. add the program code of the readerdirectory (string path, string filter) method to the CS file. This method reads the content of all files under the specified directory (specified by the path parameter) that meet the filter (specified by the filter parameter) and returns the read content. The procedure is as follows: ① determine whether the path parameter is valid. If it is invalid, the method is aborted. ② Create a stringbuilder class instance content that stores the read content. ③ If the filter parameter is null, you can directly call readersubdirectory (string path, string filter, ref stringbuilder content) to read the content of all files in the directory (and its subdirectories) specified by the path parameter. ④ If the filter parameter is not empty, first convert the filter into a string array filters, then use the foreach statement to process each type of files in the filters array, and read the path directory (and its subdirectories) content of all files that meet the filter. ⑤ The content of the file read above is saved in the content variable. Finally, convert the variable to a string and return the string. Based on the above, the program code of the readerdirectory (string path, string filter) method is as follows: 1. /// <summary> Read all files in the specified directory </Summary> 2. public static string readerdirectory (string path, string filter) 3. {// determine whether the directory is correct. 4. if (string. isnullorempty (PATH) = true) return string. empty; 5. stringbuilder content = new stringbuilder (); 6. /// Save the read content 7. /// if the filter is null, the system reads the content of all files by default. if (string. isnullorempty (filter) = true) 9. {10. reader Subdirectory (path, filter, ref content); 11 .} 12. else 13. {// If the filter is not empty, obtain the file to be read. 14. string [] Filters = filter. split (New char [] {'|'}, 15. stringsplitopti/ons. removeemptyentries); 16. /// read the content of each file 17. foreach (string fi in filters) {readersubdirectory (path, Fi, ref 18. content);} 19 .} 20. return content. tostring (); 21 .} (5) In program. call readerdirectory (string path, String filter) read the contents of all files with the suffix. CS in the "C: \ data" directory and display them in the console. The program code is as follows: 1. static void main (string [] ARGs) 2. {// read the contents of all files ending with ", CS" in the "C: \ data" directory. and display 4. console. writeline (readerdirectory (@ "C: \ data ","*. CS "); 5. console. read (); 6 .} (6) Press F5 in the integrated development environment of Visual Studio 2008 to run the sample_21 application. The console displays the following results: 1. using system; 2. using system. collecti/ons; 3. using system. text; 4. using system. i/O; 5. using system. windows. forms; 6. 7. namespace dorient. fileparse. component 8. {9. public class file 10. {11.... 12. /// write the file 13. streamwriter writer = new streamwriter (path, false, 14. encoding. default); 15. writer. write (content); 16. writer. close (); 17 .} 18. catch (Ti/on ex) 19. {20. messageBox. show (ex. message, "file writing error"); 21 .} 22 .} 23 .} 24 .} 21.5 machine Practice 1. code debugging: in Visual Studio 2008 integrated development environment, debug the following code to ensure normal operation. If it runs properly, write the running result. If it cannot run properly, point out the error code and correct it. 1. namespace Test 2. {3. class program 4. {5. static void main (string [] ARGs) 6. {7. fileinfo Fi = new fileinfo ("My. ini "); 8. filestream FSR = Fi. openread (); 9. byte [] DATAR = new byte [(INT) FSR. length]; 10. FSR. read (DATAR, 0, (INT) FSR. length); 11. string valuer = system. text. encoding. unicode. getstring (DATAR); 12. console. writeline (valuer); 13. console. read (); 14 .} 15 .} 16 .} 2. programming Problems in Visual Studio 2 In the integrated development environment, a console application named fileoperationis created and read and write the readme.txt file. 21.6 FAQs: How to traverse all directories (excluding subdirectories) and files under a directory and display the names of directories and files? A: directly use the foreach statement and the method in the Directory class. The program code is as follows. 1. String Path =... /// Directory to be traversed 2. directoryinfo parentdi = new directoryinfo (PATH); 3. /// create an instance in the directory specified by Path 4. foreach (directoryinfo di in parentdi. getdirectories () 5. /// access the subdirectory 6 of the current directory. {7. console. writeline (Di. name); 8. /// display the subdirectory name 9 .} 10. foreach (fileinfo fi in parentdi. getfiles () 11. /// access the file in the current directory 12. {13. console. writeline (Fi. name); 14. /// display the file name 15 .}

 

Related Article

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.