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 –
//Copy it to another file. Delete first file.
//Move File to another directory, get the file extension and file name******
/*
if (Directory.Exists(dirPath))
{
var readFiles = Directory.GetFiles(dirPath, “*.*”);
{
Console.WriteLine(i);
}
if (sourceDir.Exists)
{
var readFiles = sourceDir.GetFiles();
{
Console.WriteLine(i);
}
using (FileStream fw = fileToWrite.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes(“sdkjfhsdjfhsdkjfh sdkjfbdsfj kjsdfdsf”);
fw.Write(txt,0,txt.Length);
}
fileToWrite.CopyTo(fileCopyPath,true);
var fileToRead = new FileInfo(fileCopyPath);
using (FileStream fwStream = fileToRead.OpenRead())
{
var b = new byte[1024];
{
Console.WriteLine(temp.GetString(b));
}
}
}