C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# FileInfo ClassThe FileInfo class is used to deal with file and its operations in C#. It provides properties and methods that are used to create, delete and read file. It uses StreamWriter class to write data to the file. It is a part of System.IO namespace. C# FileInfo Class Signature[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class FileInfo : FileSystemInfo C# FileInfo ConstructorsThe following table contains constructors for the FileInfo class.
C# FileInfo PropertiesThe following table contains properties of the FileInfo class.
C# FileInfo MethodsThe following table contains methods of the FileInfo class.
C# FileInfo Example: Creating a Fileusing System; using System.IO; namespace CSharpProgram { class Program { static void Main(string[] args) { try { // Specifying file location string loc = "F:\\abc.txt"; // Creating FileInfo instance FileInfo file = new FileInfo(loc); // Creating an empty file file.Create(); Console.WriteLine("File is created Successfuly"); }catch(IOException e) { Console.WriteLine("Something went wrong: "+e); } } } } Output: File is created Successfully We can see inside the F drive a file abc.txt is created. A screenshot is given below. C# FileInfo Example: writing to the fileusing System; using System.IO; namespace CSharpProgram { class Program { static void Main(string[] args) { try { // Specifying file location string loc = "F:\\abc.txt"; // Creating FileInfo instance FileInfo file = new FileInfo(loc); // Creating an file instance to write StreamWriter sw = file.CreateText(); // Writing to the file sw.WriteLine("This text is written to the file by using StreamWriter class."); sw.Close(); }catch(IOException e) { Console.WriteLine("Something went wrong: "+e); } } } } Output: C# FileInfo Example: Reading text from the fileusing System; using System.IO; namespace CSharpProgram { class Program { static void Main(string[] args) { try { // Specifying file to read string loc = "F:\\abc.txt"; // Creating FileInfo instance FileInfo file = new FileInfo(loc); // Opening file to read StreamReader sr = file.OpenText(); string data = ""; while ((data = sr.ReadLine()) != null) { Console.WriteLine(data); } } catch (IOException e) { Console.WriteLine("Something went wrong: " + e); } } } } Output:
Next TopicC# DirectoryInfo
|