Thursday, 11 May 2017

File & FileInfo

The File and FileInfo class are used to create and manipulate files and fileStreams. The File class is a static implementation while the FileInfo class is an instance implementation for dealing with files.

first let's take a look at leveraging the FileInfo instance class.

using System;
using System.IO;

namespace pc.FileInfoExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var fi = new FileInfo(@"c:\dev\FileInfo.txt");

            using (FileStream fs = fi.Create())
                fs.Close();

            using (StreamWriter sw = fi.AppendText())
                try
                {
                    sw.WriteLine("This is a test");
                    sw.WriteLine("And this is line two");
                }
                finally
                {
                    sw.Close();
                }

            Console.WriteLine("Directory:\t" + fi.DirectoryName);
            Console.WriteLine("Creattion:\t" + fi.CreationTime);
            Console.WriteLine("File Path:\t" + fi.FullName);
            Console.WriteLine("Extension:\t" + fi.Extension);
            Console.WriteLine("Last Access:\t" + fi.LastAccessTime);
            Console.WriteLine("File Size:\t" + fi.Length + " bytes");
            Console.WriteLine("File Name:\t" + fi.Name);

            using (StreamReader sr = fi.OpenText())
                try
                {
                    string line = "";

                    while ((line = sr.ReadLine()) != null)
                        Console.WriteLine(line);
                }
                finally
                {
                    sr.Close();
                }
        }
    }
}


now let's take a look at the same thing but using the static File class

using System;
using System.IO;

namespace pc.FileExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string FilePath = @"c:\dev\File.txt";

            using (FileStream fs = File.Create(FilePath))
                fs.Close();
          
            Console.WriteLine("Creation:\t" + File.GetCreationTime(FilePath));

            File.WriteAllLines(FilePath,
                new string[] {"This is only a Test", "And this is line two"});

            string[] lines = File.ReadAllLines(FilePath);
            foreach (var line in lines)
                Console.WriteLine(line);
        }
    }
}


now it's very similar and for the most part it will come down to the individual details of needs and personal preferences.