Creating Objects In C#

Creating a DirectoryInfo or FileInfo object is very simple. The constructor takes the path to the file.
 
DirectoryInfo di = new DirectoryInfo(“C:\\Windows”);
FileInfo fi = new FileInfo(“C:\\Windows\\Notepad.exe”);
 
Listing All Files in a Directory
 
The following code snippet lists all the files in the “C:\Windows” directory.
 
DirectoryInfo di = new DirectoryInfo("C:\\Windows");
FileInfo[] fis = di.GetFiles();
foreach (FileInfo fi in fis)
{
    Console.WriteLine(fi.Name);
}
 
Practical Example (FileHandling):
 
testFileHandling.cs
 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace testFileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter
(@"C:\Documents and Settings\Administrator\Desktop\date.txt");

            // write a line of text to the file
            Console.WriteLine("Please enter your text---\n");
            string aa = Console.ReadLine();

            tw.WriteLine(aa);

            // close the stream
            tw.Close();
            Console.ReadLine();
            // create reader & open file
            
            TextReader tr = new StreamReader
(@"C:\Documents and Settings\Administrator\Desktop\date.txt");

            // read a line of text
            Console.WriteLine("The file contain the text---\n");

            Console.WriteLine(tr.ReadToEnd());

            // close the stream
            tr.Close();
            Console.ReadLine();
        }
    } 
}
 
The Output is:
 
img
 
To Download File Handling example Click here.
 
To view downloaded examples, Please Ensure that .NET Framework is installed on your system.
Scroll to Top