Wednesday, August 28, 2013

C# - Working with File System Objects(Part 2)

This article is the second from the “Working with File System Objects” series (the first article covered the “Directory” class), this article will cover the “DirectortInfo” class that located under the system.Io namespace.

DirectoryInfo Class
Not like the “Directory” class that expose only static methods the DirectoryInfo class exposed only instances. Therefore you must initialize a new class object before you can use it.

Note!
To use this class please add the “System.IO” namespace.

Class Summary:
This table contain the main methods you can use while working with this class.

Method Name
Why to use?
Instance.Create();
When you need to Create folder
Instance.Attributes
When you need to verify the object type (Folder or File)
Instance.Parent
When you need to get the parent folder
Instance.CreationTime
When you need to extract the folder creation time
Instance.FullName
When you need to get the folder full path
Instance.Name
When you need to get a specific folder name
Instance.Root
When you need the folder partition
Instance.Exists;
When you need to check if folder existing

 

Code Examples:

Create Folder


This example create a new folder, all you need is to pay attention that you need to add the new folder path when initialize the new class instance.

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder"); 
            a.Create();
        }

Validate Folder existence

This example will verified if folder existing on your File System tree

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.Exists); //True OR False
        }

Folder creation time

This example will return the folder creation date

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.CreationTime);
        }

Receiving the folder full path

This example will return the folder full path

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.FullName);
        }

Returning the folder name

This property will return the folder name and not the full path.

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.Name);
        }

Returning the root partition

This prop will return the folder partition for a given folder

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.Root);
        }

Validate the object type

This prop will be used when you want to validate if the object is file or folder

static void Main(string[] args)
        {
            DirectoryInfo a = new DirectoryInfo("c:\\New Folder");
            Console.WriteLine(a.Attributes);
        }

Monday, August 26, 2013

C# - Working with File System Objects (Part 1)

This article will be the first one from a series of articales that will cover System I\O operations you can covered using C# classes.

Classes for I/O operations
C# contain multiple classes that we can used to handle I/O operations (Files /Folders) for this article you need to add the following 'using' in your code:

using System.Text;
using System.Threading.Tasks;
using System.IO;

By adding this namespace we now have access to different classes that can help us perform multiple operations on files and folders.

Main classes in System.Io namespace:

Class Directory

This class contain static methods for Directories manipulation, using this class you can do multiple operations for folders without using/Creating instances from class.

Class Summary:
This table contain the main methods you can use while working with this class.

Method Name
Why to use?
Directory.Delete
When you need to Remove folder
Directory. Create
When you need to Create folder
Directory.GetFiles
When you need to get list of files under specific path
Directory.GetDirectories
When you need to get list of folders under specific path
Directory.GetCreationTime
When you need to extract the folder creation time
Directory.GetParent
When you need to get the folder parent folder
Directory. Move
When you need to move folder for different location
Directory.GetLogicalDrives
When you need to get your server logical drives
Directory.Exist
When you need to check if folder existing

Code Examples:

Create Folder

This example create root folder under root drive with inner folder.
Directory.CreateDirectory("C:\\New Folder\\SubFolder");             
       

Add Folder for existing Tree

This code will add folder into the root folder we created on previous step:
Directory.CreateDirectory("C:\\New Folder\\SubFolder1");


Delete Folder

Example 1:
This code will delete an ‘Empty’ folder (No files or folder under given path)
Directory.Delete("C:\\New Folder\\SubFolder1");

Note!
Id objects resides under this path the program will crush with “IOException” error.

Example 2:
This code will delete root folder + sub objects (Folder /Files)

Directory.Delete("C:\\New Folder",true);


Note!
If folder opened or used by another process the software failed with “IOException error”


Check for folder existence under specific folder

This example send query to validate if specific folders located under a Directory path

Directory.Exists("C:\\New Folder\\SubFolder");           


Extract the Root folder for specific path

This code will return the folder that host the folder supplied in method
string  RootFolder = Directory.GetDirectoryRoot("c:\\1");

Note!
You can also extract the project current directory when using the “Directory.GetCurrentDirectory();” method.


Extracting dates for specific operations

This part will show how to receive dates for specific operations performed on a given folder

Creation Time:
DateTime FolderCreation2 = Directory.GetCreationTime("c:\\1");

Last modification time:
DateTime LastModificationTime = Directory.GetLastWriteTime("c:\\1");


Extracting the computer logical drives

This code will extract all logical drives located on computer, pay attention that we need to use an array to host the returned values.

string [] LogicalDrives = Directory.GetLogicalDrives();

            foreach (var item in LogicalDrives)
            {
                Console.WriteLine(item);
            }


Extract folder list under specific path

This code will demonstrate how to extract the folder tree under specific path

string [] ArrayOfDirectories = Directory.GetDirectories("c:\\");

            foreach (var item in ArrayOfDirectories)
            {
                Console.WriteLine(item);
            }
Note!
You can use search patter by using:

string[] SearchByPattern = Directory.GetDirectories("c:\\1", "FolderNmae");


Extract files list under specific path

This code will demonstrate how to extract the files tree under specific path

string [] ArrayOfFiles = Directory.GetFiles("c:\\1");

            foreach (var item in ArrayOfFiles)
            {
                Console.WriteLine(item);
            }

Note!
You can use search patter by using:

string[] ArrayOfFiles = Directory.GetFiles("c:\\1", "Filename");


Saturday, August 24, 2013

C# - Conditions(IF and Else)

Conditions help you to control the code flow of your software based on the condition result (True OR False).

When the compiler runs your code he need to decide the “Code Directions” , means that in some cases the compiler should start in point A and move to point B  and in another cases he need to start in point A and move to point C .

Conditions can be configured with ‘IF’ and ‘Else’ statements, Example:
Example 1:

Class Program
    {
        static void Main(string[] args)
        {
            int a = 1 , b =2 ;
            if (a > b )
            {
                //Execute This code                
            }
            else
            {
                //Execute This code               
            }
        }
    }

As you can see it’s very simple, the compiler start processing your code and when he gets to the ‘IF’ statement he checks the result (True / False) and then decide to execute the relevant code.
Example 2:

In some cases we want to execute specific code part only  if the ‘IF’ statement return ‘true’ but if the statement return false we doesn’t want to execute any  another code  .
class Program
    {
        static void Main(string[] args)
        {
            int a = 1 , b =2 ;
            if (a > b ) //If True
            {
                //Execute This code               
            }
            //If 'False'
     
            //Additional Code that doesn’t relevant for the 'IF' statement
        }
    }

Example 3:
In some cases we want to use ‘Nested’ conditions logic to resolve a complicated issues.

class Program
    {
        static void Main(string[] args)
        {
            int a = 2, b = 1;
            if (a > b) //If True
            {
                if (a < 3)
                {
                    //This code executed
                }
                if (a > 3)
                {
                    //This code executed
                }
                if (a == 3)
                {
                    //This code executed
                }
            }
            else
            {
                //Executed this code
            }
        }
    }

In this code you can see that if a>b we executing the code in this block based on 3 different conditions, if a <= b the compiler will executed the code in the ‘Else’ bulk.

Example 4:
In some cases we can use “Else If” statement when we know a specific range of the variable initialization

In this example a can be set with the range of 1, 2 and 3, therefore we can use “Else if” OR ‘switch’ condition

class Program
    {
        static void Main(string[] args)
        {
            Random a = new Random();
            int number = a.Next(1,3);
            if (number == 1)
            {
             //Ececute this code
            }
            else if (number == 2)
            {
            //Ececute this code  
            }
            else if (number == 3)
            {
             //Execute this code
            }
        }
    }

Complex conditions  
In some cases we want to execute our code after more the one verification, therefore we can use 2 different operators (And / OR) that could be used alone OR with combination.

Example 1 (AND):
As you can see, the code will be executed only when 2 different condition return ‘True’, if one of the conditions return ‘false’ the code will not be executed.

 Class Program
   {
        static void Main(string[] args)
        {
            Random a = new Random();
            int number = a.Next(0,2);
            if ((number == 0) && (number < 2))
            {
             //Ececute this code
            }                       
        }
    }

Example 2 (OR):
In this case the code will be executed when only one condition return ‘True’.
Class Program
    {
        static void Main(string[] args)
        {
            Random a = new Random();
            int number = a.Next(0,2);

            if ((number == 0) || (number < 2))
            {
             //Ececute this code
            }                       
        }
    }

Example 3 (Or / And):
In this case I created a combination of the two operators to give an example for complex statement.

class Program
    {
        static void Main(string[] args)
        {
            Random a = new Random();

            int number = a.Next(0,100);
            int number2 = a.Next(0,100);

            if (((number < 10) || (number2 < 10)) && ((number < 5 || (number2 == 10))))
            {
             //Ececute this code
            }
            else if (((number < 10) && (number2 < 10)) || ((number < 5 && (number2 == 10))))
            {
               //Ececute this code
            }
            else if (((number < 10) && (number2 < 10)) && ((number < 5 && (number2 == 10))))
            {
                //Ececute this code
            }
            else if (((number < 10) && (number2 < 10)) && ((number < 5 || (number2 == 10))))
            {
                //Ececute this code
            }
        }
    }


Using short conditions
After reviewing the conditions statement,
I now can explain how to create the same statement with less syntax.
To write conditions with less syntax, you can use the following format:

Variable = (Boolean Condition)? “Positive”: “Negative”
Example:

class Program
    {
        static void Main(string[] args)
        {
            Random a = new Random();
            int number =  5;
            int number2 = 4;

            //Short Condition :
            string ConditionResult = (number > number2) ? "Bigger" : "Lower";
            Console.WriteLine(ConditionResult);
                     //Result = "Bigger"
           
            //Regular Condition:
            string B = "Bigger";
            string L = "Lower";
            if (number > number2)
            {
                Console.WriteLine(B);
            }
            else
            {
                Console.WriteLine(L);
            }
            //Result = "Bigger"
        }
    }

My Presentations