為了在.NET框架中處理文件,使用的重要命名空間是system.IO命名空間,類似地,我們在C#中有一個名為FileInfo類的類,它不包含靜態方法,只有實例化對象才能使用該類,磁碟上的文件或網絡位置由fileinfo 對象表示,文件流對象可以在fileinfo 對象的幫助下創建,文件信息類提供實例方法來創建、刪除、複製、移動和打開文件我們可以更好地控製檔案的讀寫操作,使用fileinfo 類別手動編寫可以從檔案讀取的程式碼或可以寫入位元組的程式碼。
C# FileInfo 類別的語法如下:
[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class FileInfo : FileSystemInfo
要了解 C# 中 FileInfo 類別的工作原理,我們需要了解 FileInfo 類別的建構子、FileInfo 類別的屬性和 FileInfo 類別的方法。
FileInfo 類別的建構子解釋如下:
FileInfo 類別有多個屬性。它們的解釋如下:
FileInfo 類別有多種方法。它們的解釋如下:
As we have understood the constructors of FileInfo class, Properties of FileInfo class and methods of the FileInfo class, now consider the below program:
Code:
using System; using System.IO; namespace Program { class Check { static void Main(string[] args) { try { // the file location is specified where the file is to be created string location = "C:\Users\shivakumarsh\Desktop\new.txt"; // instance of the fileinfo class is created FileInfo file = new FileInfo(location); // an empty file is created file.Create(); Console.WriteLine("Creation of file is successfull"); } catch(IOException e) { Console.WriteLine("Failed attempt to create file "+e); } } } }
Output:
In the above program, a namespace called the program is declared. Then the main method consisting of the try-catch block is defined. The try block consists of the location string where the new file needs to be created. An instance of the file info class is created, and the location string is passed as a parameter to the instance of the file info class. Create () method is invoked on the object of the file info class to create a new file in the location specified by the location string. If the file creation is successful, the success message is printed otherwise an exception is raised which is included in the catch block.
C# program to demonstrate usage of File Info class.
Code:
using System; using System.IO; namespace Program { class Check { static void Main(string[] args) { // the file location is specified where the file is to be located string location = "C:\Users\shivakumarsh\Desktop\new.txt"; // instance of the fileinfo class is created FileInfo file = new FileInfo(location); // The specified file is deleted file.Delete(); Console.WriteLine("Deletion of file is successfull"); } } }
Output:
In this tutorial, we understand the concept of FileInfo class in C# through definition, constructors of FileInfo class, properties of FileInfo class, methods of FileInfo class, working of FileInfo class through examples.
以上是C# 文件訊息的詳細內容。更多資訊請關注PHP中文網其他相關文章!