C# – Drive, Directory and File

Standard
  • .Net has the feature to find the Drives, Directories and Files info, to create, delete directories and files, to get directory and file List, to write, append and read contents of the files using System.IO.
  • .Net has the feature to allow, deny to access the file system in code level usingCodeAccessPermission, and find the Permission, Access Rule using System.Security, System.Security.AccessControl, System.Security.Permission.

using System;

using System.IO;

using System.Security;

using System.Security.AccessControl;

using System.Security.Permissions;

using System.Text;

using System.Text.RegularExpressions;

namespace ReadWriteFie

{

class Program

{

static string strFolderList = string.Empty;

static string strFileList = string.Empty;

static int iFolders = 0;

static int iFiles = 0;

static void Main(string[] args)

{

string strPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

//deneyFilePermission( @”C:\”);

//assertFilePermission(@”C:\”);

//StreamReader sr = File.OpenText(@”C:\Testfile.txt”);

//writeFileA(@”C:\”, “Testfile.txt”, “Testing contents “);

//writeFileB(@”C:\”, “Testfile.txt”, “Testing contents “);

//Console.Write(“Starting read .”);

//readFile(strPath, “Testfile.txt”);

//driveInfo();

//directoryInfo(strPath);

//fileInfo(strPath, “Testfile.txt”);

//DirectoryInfo dirInfo = new DirectoryInfo(strFolderList += strPath);

//Console.WriteLine(String.Format(“Directory List : {0} “, strFolderList ));

//strFileList += getFileList(dirInfo);

//writeFileA(strPath, “getFileList.txt” , getSubdirectoryList(dirInfo));

//Console.WriteLine(String.Format(“Number of Folders : {0} , Number of Files : {1}”, iFolders, iFiles));

//checkDirAccessControl(strPath);

//checkFileAccessControl(strPath + @”\Testfile.txt”);

Console.ReadLine();

}

//static void deneyFilePermission(string strPath)

//{ // using System.Security;

// // using System.Security.Permissions;

// // Implicit control of file permission sing CodeAccessPermission : Deny

// CodeAccessPermission fip = new FileIOPermission(FileIOPermissionAccess.AllAccess, strPath);

// fip.Deny();

//}

//static void assertFilePermission(string strPath)

//{ // using System.Security;

// // using System.Security.Permissions;

// // Implicit control of file permission sing CodeAccessPermission : Assert

// FileIOPermission fip = new FileIOPermission(FileIOPermissionAccess.AllAccess, strPath);

// fip.Assert();

//}

//static void revertDeny()

//{

// //using System.Security;

// // Explicit control of file permission using CodeAccessPermission : RevertDeny

// CodeAccessPermission.RevertDeny();

//}

//static void revertAssert()

//{

// //using System.Security;

// // Explicit control of file permission using CodeAccessPermission : RevertAssert

// CodeAccessPermission.RevertAssert();

//}

static void checkDirAccessControl(string strDirPath)

{ // using System.IO;

// using System.Security.AccessControl;

// Check directory access control – I am also new to this

DirectoryInfo dirInfo = new DirectoryInfo(strDirPath);

DirectorySecurity dirSecrity = dirInfo.GetAccessControl();

foreach (FileSystemAccessRule FSAccessRule in dirSecrity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)))

{

Console.WriteLine(“Directory : {0}, \r\n\t Access Control Type : {1}, \r\n\t\t File System Rights : {2}, \r\n\t\t\t Identity Reference : {3} \r\n”, strDirPath, FSAccessRule.AccessControlType.ToString(), FSAccessRule.FileSystemRights, FSAccessRule.IdentityReference );

}

}

static void checkFileAccessControl(string strFilePath)

{ // using System.IO;

// using System.Security.AccessControl;

// Check file access control – I am also new to this

FileInfo fileInfo = new FileInfo(strFilePath);

FileSecurity fileSecrity = fileInfo.GetAccessControl();

foreach (FileSystemAccessRule FSAccessRule in fileSecrity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))

{

//please check the figure below for difference between System.Security.Principal.NTAccount and System.Security.Principal.SecurityIdentifier

Console.WriteLine(“File : {0}, \r\n\t Access Control Type : {1}, \r\n\t\t File System Rights : {2}, \r\n\t\t\t Identity Reference : {3} \r\n”, strFilePath, FSAccessRule.AccessControlType.ToString(), FSAccessRule.FileSystemRights, FSAccessRule.IdentityReference);

}

}

static string makeFilePath(string strPath, string file)

{

//using System.Text.RegularExpressions;

//Check presence of last back slash”\”

if (!Regex.IsMatch(strPath, @”\S*\\$”))

strPath = strPath + @”\”;

return strPath + file;

}

static bool writeFileA(string strPath, string file, string strContents )

{

//using System.IO;

FileStream Fs = newFileStream(makeFilePath(strPath, file), FileMode.Append, FileAccess.Write);

byte[] byteContents = Encoding.UTF8.GetBytes(strContents.ToCharArray()); // using System.Text – Get bytes

int ibyteCount = Encoding.UTF8.GetByteCount(strContents.ToCharArray()); // using System.Text – Get byte Count

try

{

Fs.Write(byteContents, 0, ibyteCount);

Fs.Close();

return true;

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

return false;

}

}

static bool writeFileB(string strPath, string file, string strContents )

{ // using System.IO;

//Using StreamWriter to write the portion of the contents.

int iContentFrom = 5;

int iLengthOfContents = 5;

StreamWriter sw = new StreamWriter(makeFilePath(strPath, file), false, Encoding.ASCII);

sw.WriteLine(strContents.ToCharArray(), iContentFrom, iLengthOfContents);

sw.Close();

return true;

}

static string readFile(string strPath, string file)

{

// using System.IO;

// Read file Contents

string strContents = string.Empty;

string tempContents = string.Empty;

StreamReader sr = new StreamReader(makeFilePath(strPath, file));

while (( tempContents = sr.ReadLine()) != null)

{

strContents += tempContents;

Console.Write(“.”);

}

Console.WriteLine(strContents);

return strContents;

}

static bool createFile(string strFile)

{ // using System.IO;

//if (!(File.Exists(strFile)))

// File.Create(strFile);

FileInfo fi = new FileInfo(strFile);

try

{

if (!(fi.Exists))

fi.Create();

return true;

}

catch (IOException IOE)

{

Console.WriteLine(IOE.ToString());

return false;

}

}

static bool createDirectory(string strDirPath)

{ // using System.IO;

// DirectoryInfo dirInfo = new DirectoryInfo(strDirPath);

// dirInfo.Create();

try

{

if (!(Directory.Exists(strDirPath)))

Directory.CreateDirectory(strDirPath);

return true;

}

catch(IOException IOE)

{

Console.WriteLine(IOE.ToString());

return false;

}

}

static void driveInfo()

{

// using System.IO;

// get driver information

DriveInfo di = new DriveInfo(@”D:\”);

Console.WriteLine(String.Format(“Drive Name \t\t\t: {0} “,di.Name));

Console.WriteLine(String.Format(“Drive Volume Lable \t\t: {0} “, di.VolumeLabel));

Console.WriteLine(String.Format(“Drive root directory \t\t: {0}”, di.RootDirectory));

Console.WriteLine(String.Format(“Drive Format \t\t\t: {0}”, di.DriveFormat));

Console.WriteLine(String.Format(“Drive Total Size \t\t: {0} bytes”, di.TotalSize));

Console.WriteLine(String.Format(“Drive Total Free Size \t\t: {0} bytes”,di.TotalFreeSpace));

Console.WriteLine(String.Format(“Drive Available Free Size \t: {0} bytes”, di.AvailableFreeSpace));

}

static string getSubdirectoryList(DirectoryInfo dirInfo)

{ // using System.IO;

// get Sub directories list from Directory

foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories())

{

Console.WriteLine(“Directory List : {0} “, strFolderList += subDirInfo.FullName + “\r\n” );

getFileList(subDirInfo);

iFolders++;

getSubdirectoryList(subDirInfo);

}

return strFileList;

}

static string getFileList(DirectoryInfo dirInfo)

{ // using System.IO;

// get files list from directory

foreach (FileInfo fileInfo in dirInfo.GetFiles())

{

Console.WriteLine(“File List : {0} “, strFileList += fileInfo.FullName + “\r\n”);

iFiles++;

}

return strFileList;

}

static void directoryInfo(string strPath)

{

// using System.IO;

// get directory information

DirectoryInfo dirInfo = new DirectoryInfo(strPath);

Console.WriteLine(String.Format(“Directory Full Name \t\t: {0} “, dirInfo.FullName));

Console.WriteLine(String.Format(“Directory Extension \t\t: {0} “, dirInfo.Extension));

Console.WriteLine(String.Format(“Directory Creation Time \t: {0} “, dirInfo.CreationTime));

Console.WriteLine(String.Format(“Directory Creation Time UTC \t: {0} “, dirInfo.CreationTimeUtc));

Console.WriteLine(String.Format(“Directory Attributes \t\t: {0} “, dirInfo.Attributes));

}

static void fileInfo(string strPath, string file)

{

// using System.IO;

// get file information

FileInfo fileInfo = new FileInfo(makeFilePath(strPath, file));

Console.WriteLine(String.Format(“Directory Name \t\t : {0}”,fileInfo.DirectoryName));

Console.WriteLine(String.Format(“Directory \t\t : {0}”, fileInfo.Directory));

Console.WriteLine(String.Format(“File Full Name \t\t : {0}”, fileInfo.FullName));

Console.WriteLine(String.Format(“File Extension \t\t : {0}”,fileInfo.Extension ));

Console.WriteLine(String.Format(“File Creation Time \t : {0}”,fileInfo.CreationTime));

Console.WriteLine(String.Format(“File Creation TimeUtc \t : {0}”,fileInfo.CreationTimeUtc));

Console.WriteLine(String.Format(“File Attribtes \t\t : {0}”,fileInfo.Attributes));

}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s