Tuesday, September 3, 2013

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

Copy file

This section will demonstrate how to copy specific file into different location.
The ‘Copy’ method should receive 3 parameters:

Source File = "c:\\1.txt",
Destination Location = "c:\\1\\1.txt"
Overwrite if existing = true

static void Main(string[] args)
        {
            File.Copy("c:\\1.txt", "c:\\1\\1.txt",true);        
        }

Result:

Delete file
This code will demonstrate how to delete file from your file system
The ‘Delete’ method receive a single parameter for the file location you want to delete.

static void Main(string[] args)
        {
            File.Delete("c:\\1.txt");        
        }


Check if file exists

This code is checking if the file exists on your file system, the method receive single parameter (file path) and return Boolean value (True OR False)

static void Main(string[] args)
        {
            Console.WriteLine(File.Exists("c:\\1.txt"));              
        }

Result :
















Move  file

This part will demonstrate how to ‘Move’ a file to a different location, in your Win OS it’s equal to “Cut->Paste”. Furthermore, this method allow you to move the file with his original name or changing the name while moving it.

Note!
This method doesn’t have the option to ‘Overwrite’ a file if the file already existing, therefore you must use the ‘Existing’ method to save failures in your application.

Option 1:
Moving the file with the same name

static void Main(string[] args)
        {
            File.Move("c:\\1.txt", "c:\\1\\1.txt");              
        }

Option 2:
Moving the file with a new name

static void Main(string[] args)
        {
            File.Move("c:\\1.txt", "c:\\NewName.txt");              
        }

Option 3:
This code will show you how to combine the ‘Existing’ method while moving the file, this code is the recommended one.

In the code  you can see that I check if the file exists on destination , if the response is ‘True’ I’m moving the file with different name , if the response is ‘False’ I’ll move the file with the same name

static void Main(string[] args)
        {
            if  (File.Exists("c:\\1\\2.txt"))
            {
                File.Move("c:\\2.txt", "c:\\MoveWithNewName.txt");
            }
            else
            {
                File.Move("c:\\2.txt", "c:\\2.txt");
            }                   
        }


Extracting specific file dates

This part will show how to extract specific dates for file operation (Creation Time, Accessing Time and last modification time)

static void Main(string[] args)
        {
            DateTime FileCreationDate = File.GetCreationTime("c:\\file.txt");
            DateTime FileLastAccess = File.GetLastAccessTime("c:\\file.txt");
            DateTime FileLastWriteTime = File.GetLastWriteTime("c:\\file.txt");
          
            Console.WriteLine(@"The file created on : {0}
The file last accessed in : {1}
The last modification on file : {2}"
 , FileCreationDate,FileLastAccess,FileLastWriteTime);  
        }

Result:






Replace content of a file

The replace method perform multiple operations, the main cause to use it is when you need to change a content of existing file with the content of another one.

Note!
The source file deleted after the operation completed.

The replace method should receive 3 parameters:
Source file – the file with the content you want to move.

Destination file – the file that host the source content (remember that this method will delete the source file after the transferring completed).

Backup file – this file will host the source file.

Code Example:

static void Main(string[] args)
 {
    File.Replace("c:\\SourceFile.txt", "C:\\DestenationFile.txt", "C:\\BackupFile.txt");        
 }


Append new lines to a file

This method add new lines to a file, existing lines will not be deleted. The method receive three different parameters:

Source file – if the file existing on your file system you should specify it.
Strings Array – you need to supply a string array that will be used to add the new lines.

Encoding type – here you should specify the encoding type that will be used wile appending the new lines.

Note!
If the source file doesn’t exists, a new file will be created instead.

Code Example:

class Program
    {
        static void Main(string[] args)
        {
            string[] text = { "Line1", "Line2", "Line3" };
            File.AppendAllLines("c:\\File1.txt", text, Encoding.UTF8);

            //Or

        File.AppendAllLines("c:\\NewFile.txt", new string []{"1","2"}, Encoding.Default);
        }
    }


Result : 

Append single line to a file

This method just add a single line to a file , just like the previous section if the file doesn’t exists it will be created while executing the operation.

The method receive only 2 parameters:

Source file – the file you want to add a new Line
String – the string you want to add.

Code:
static void Main(string[] args)
        {

            File.AppendAllText("c:\\File1.txt", "specific line");
        }

Result : 








Read all lines from a file (1)
This method read all lines from a file, this is useful when you want to create a strings array with a TXT file content.

The following code reads all lines from a ‘txt’ file and insert them into array of strings, every cell int the array contain single line from the file.


static void Main(string[] args)
        {        
            string [] FileLines = File.ReadAllLines("c:\\File1.txt",Encoding.UTF8);
            foreach (var LineInFile in FileLines)
            {
                Console.WriteLine(LineInFile);
            }
        }


Result : 














Read all lines from a file (2)

This method read all lines from a file, this is useful when you want to add the entire file content into a single string.

The following code reads all lines from a ‘txt’ file and insert them into a single string.

class Program
    {
        static void Main(string[] args)
        {        
            string FileContent = File.ReadAllText("c:\\File1.txt",Encoding.UTF8); 
            Console.WriteLine(FileContent);
        }
    }

Result:



2 comments:

  1. I suggest you use the @ sign for literal strings, which makes string variables which store paths more readable and maintainable:
    var tempFile = @"C:\My\Directory\temp.txt";

    ReplyDelete
  2. 10x,
    If you check my other articles you will see that I use '@' in many cases, for this specific demonstration I skipped it.
    But you gave a great comment here … 

    ReplyDelete

My Presentations