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

Source: Internet
Author: User
Tags array to string
OpenFileDialog openFileDialog1 = new OpenFileDialog ();


If (openFileDialog1.ShowDialog () = DialogResult. OK)
{
OpenFileDialog1.FileName;
System. IO. FileInfo file = new System. IO. FileInfo (openFileDialog1.FileName );

File. Name; // file Name
File. Length. ToString (); // size ",
File. LastAccessTime. ToString (); // last access time
File. LastWriteTime. ToString (); // last modification time
File. 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

Description of ownership description
Directory get parent Directory
Exists specifies whether the current file Exists
DirectoryName: Obtain the complete path of the file.
Length: obtains the size (in bytes) of the current file)
IsReadOnly gets or sets whether the current file is read-only
Name: get the file Name
Like the DirectoryInfo class, FileInfo also includes attributes inherited from 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 instance method table of the FileInfo class

Fang Fa Ming
Create () Create a file
OpenRead () open a file in read-only mode
Delete () Delete a specified object
OpenWrite () open a file in write-only mode
MoveTo () Move the specified file to a new location
CreateText () creates a StreamWriter that writes data to a new text file.
CopyTo () copy existing files to new files
OpenText () Open the specified text file and prepare to read the content from the file
Replace () uses the content of another file to Replace the content of the specified file AppendText () to create a StreamWriter. It can append the content of the text file to Open () to Open the file.
The Create (), Delete (), MoveTo (), CopyTo (), and Replace () methods are used to operate files, they can be used to create, delete, move, copy, and replace objects in sequence.

21.3.3 create a file

To Create a File, you can use the Create () method of the File class or the Create () method of the FileInfo class.

[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 the my. ini file, and then calls the Create () method to Create the file. The newly created my. ini file is saved in the directory where the application is located.

21.3.4 write files

There are multiple methods to write the specified content to a File, such as the OpenWrite () method of the File class and the OpenWrite () method of the FileInfo class.

[Example 21-19] use the OpenWrite () method of the FileInfo class to "this is a configuration file. "To write a string to a file named my. ini, follow these steps:

(1) create a FileInfo class instance fi, 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.

FileInfo fi = new FileInfo ("my. ini ");
/// Create a FileInfo class instance fi
FileStream fsw = fi. OpenWrite ();
/// Use OpenWrite () to open the my. ini file
String valuew = "this is a configuration file. ";
/// Set the written content
Byte [] dataw = System. Text. Encoding. Unicode. GetBytes (valuew );
/// Convert to a byte array and save it as dataw
Fsw. Write (dataw, 0, dataw. Length );
/// Write the content in the dataw array to the my. ini file
Fsw. Close ();
/// Call the Close () method of the fsw instance to Close the fsw instance

Analysis: after the 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.
 

Major: the content of the my. ini file has been encoded in Unicode mode, so the actual content of the file cannot be seen.

21.3.5 reading files

There are multiple methods to read content from a specified File, such as 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.

FileInfo fi = new FileInfo ("my. ini ");
/// Create a FileInfo class instance fi
FileStream fsr = fi. OpenRead ();
/// Use OpenRead () to open the my. ini file
Byte [] datar = new byte [(int) fsr. Length];
/// Create a datar array and save the content read from the my. ini file
Fsr. Read (datar, 0, (int) fsr. Length );
/// Read the content of the my. ini file and save it to the datar Array
String valuer = System. Text. Encoding. Unicode. GetString (datar );
/// Convert the datar array to string and save it as valuer
Console. WriteLine (valuer );
/// Display the content of my. ini file
Fsr. Close ();
/// Call the Close () method of the fsw instance to Close the fsw instance

Analysis: After the preceding sample code is run, "This is a configuration file. "String.

21.3.6 move a file

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 the my. ini file is deleted.

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 the my. ini file is deleted.

21.3.7 delete an object

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 ");

The Delete () method of the FileInfo class: deletes 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 a specified type of file in the directory

[Instance 21-1] reads the content of all files under the specified directory, specified file type, and displays the read content 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.

/// <Summary> Read the object content </summary>
Public static string ReaderFile (string path)
{
String fileData = string. Empty;
Try
{// Read the object content
StreamReader reader = new
StreamReader (path, Encoding. Default );
FileData = reader. ReadToEnd ();
Reader. Close ();
}
Catch (Ti/On ex) {throw new ExceptI
/On (ex. Message, ex);} // throw an exception
Return fileData;
}

(3) Add the Program code of the ReaderSubDirectory (string path, string filter, ref StringBuilder content) method to the Program. cs file. 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:

/// <Summary> read the content of all objects in the subdirectory </summary>
Private static void ReaderSubDirectory (string path, string filter, ref
StringBuilder content)
{// Determine whether the directory is correct
If (string. IsNullOrEmpty (path) = true) return;
/// Create an instance of directory information
DirectoryInfo parentDI = new DirectoryInfo (path );
/// Read the contents of the specified file in the current directory and Its subdirectories,
Are saved to the content variable.
Foreach (FileInfo fi in parentDI.
GetFiles (filter, SearchOptI/On. AllDirectories ))
{
Content. AppendLine ();
Content. Append (ReaderFile (fi. FullName ));
Content. AppendLine ();
}
}

(4) Add the Program code of the ReaderDirectory (string path, string filter) method to the Program. 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:

/// <Summary> Read all files in the specified directory </summary>
Public static string ReaderDirectory (string path, string filter)
{// Determine whether the directory is correct
If (string. IsNullOrEmpty (path) = true) return string. Empty;
StringBuilder content = new StringBuilder ();
/// Save the read content
/// If the filter is null, the content of all files is read by default.
If (string. IsNullOrEmpty (filter) = true)
{
ReaderSubDirectory (path, filter, ref content );
}
Else
{// If the filter is not empty, obtain the file to be read.
String [] filters = filter. Split (new char [] {'| '},
StringSplitOptI/Ons. RemoveEmptyEntries );
/// Read the content of each object
Foreach (string fi in filters) {ReaderSubDirectory (path, fi, ref
Content );}
}
Return content. ToString ();
}

(5) In Program. call the ReaderDirectory (string path, string filter) method in the Main (string [] args) method of the cs file to read the Suffix in the "C: \ data" directory. the contents of all files of cs are displayed on the console. The program code is as follows:

Static void Main (string [] args)
{// Read the contents of all files ending with ", cs" in the "C: \ data" directory,
And display
Console. WriteLine (ReaderDirectory (@ "C: \ data", "*. cs "));
Console. Read ();
}

(6) Press F5 in the integrated development environment of Visual Studio 2008 to run the Sample_21 application. The console displays the following results:

Using System;
Using System. CollectI/Ons;
Using System. Text;
Using System. I/O;
Using System. Windows. Forms;

Namespace Dorient. FileParse. Component
{
Public class File
{
 
/// Write a file
StreamWriter writer = new StreamWriter (path, false,
Encoding. Default );
Writer. Write (content );
Writer. Close ();
}
Catch (Ti/On ex)
{
MessageBox. Show (ex. Message, "file writing error ");
}
}
}
}

21.5 server practices

1. Code debugging

Debug the following code in the integrated development environment of Visual Studio 2008. If it runs properly, write the running result. If it cannot run properly, point out the error code and correct it.

Namespace Test
{
Class Program
{
Static void Main (string [] args)
{
FileInfo fi = new FileInfo ("my. ini ");
FileStream fsr = fi. OpenRead ();
Byte [] datar = new byte [(int) fsr. Length];
Fsr. Read (datar, 0, (int) fsr. Length );
String valuer = System. Text. Encoding. Unicode. GetString (datar );
Console. WriteLine (valuer );
Console. Read ();
}
}
}

2. programming questions

Create a console application named fileoperationin Visual Studio 2008integrated development environment, and read and write the readme.txt file in the application.
21.6 FAQs

Q: How do I traverse all directories (excluding subdirectories) and files under a directory and display the Directory and file name?

A: directly use the foreach statement and the method in the Directory class. The program code is as follows.

String path =... /// Directory to be traversed
DirectoryInfo parentdi = new DirectoryInfo (path );
/// Create an instance in the directory specified by path
Foreach (DirectoryInfo di in parentdi. GetDirectories ())
/// Access the subdirectory of the current directory
{
Console. WriteLine (di. Name );
/// Display the subdirectory name
}
Foreach (FileInfo fi in parentdi. GetFiles ())
/// Access the file in the current directory
{
Console. WriteLine (fi. Name );
/// Display the file name
}

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.