为了在.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中文网其他相关文章!