C# File, Directory Manipulation

C# provide two versions of File, Directory manipulation options – 1) Static methods based and 2) Instance methods based. Static method based operations are provided by the File and Directory classes both derived from System.IO class. Instance method based operations are provided by the FileInfo and DirectoryInfo classes again both derived from System.IO class. File and Directory based operations are used in cases where there is less number of reads  /writes on the same location, otherwise it will lead to performance issues since the static calls will invoke security/auth checks each time the file/directory is accessed. Whereas FileInfo and DirectoryInfo are more suitable in cases where there is frequent access and the auth. is done only once when the object is instantiated. A sample usage is as below –

            //File, FileInfo, Directory, DirectoryInfo and Path class
            //******create a path to directory, list contents within it, Create a file, write some content to it.
//Copy it to another file. Delete first file.
//Move File to another directory, get the file extension and file name******
            //Implementation using static classes – File, Directory
var dirPath = @”C:\Users\user1\Desktop”;
/*
if (Directory.Exists(dirPath))
{
var readFiles = Directory.GetFiles(dirPath, “*.*”);
                foreach (var i in readFiles)
{
Console.WriteLine(i);
}
                var fileName = dirPath + @”\test.txt”;
                var fileCopyPath = @”C:\Test\test.txt”;
File.WriteAllText(fileName, “This is a test File written on ” + DateTime.Now + “. “);
                File.Copy(fileName, fileCopyPath);
                File.Delete(fileName);
            }
            //Implementation using instance classes – FileInfo, DirectoryInfo
            var sourceDir = new DirectoryInfo(dirPath);
if (sourceDir.Exists)
{
var readFiles = sourceDir.GetFiles();
                foreach (var i in readFiles)
{
Console.WriteLine(i);
}
                var fileName = dirPath + @”\test.txt”;
                var fileCopyPath = @”C:\Test\test.txt”;
                var fileToWrite = new FileInfo(fileName);
using (FileStream fw = fileToWrite.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes(“sdkjfhsdjfhsdkjfh sdkjfbdsfj kjsdfdsf”);
fw.Write(txt,0,txt.Length);
}

fileToWrite.CopyTo(fileCopyPath,true);

                fileToWrite.Delete();
                //For gun read it as well – Read File
var fileToRead = new FileInfo(fileCopyPath);
using (FileStream fwStream = fileToRead.OpenRead())
{
var b = new byte[1024];
                    var temp = new UTF8Encoding(true);
                    while (fwStream.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}

Add a Comment

Your email address will not be published. Required fields are marked *