Saturday, 28 May 2016

File

A file is collection of data stored in a disk with a specific name. When a file opened to read and write data from it. It became stream.
To use file class you need to include System.IO namespace to the project.
File class is static class and method of file class also static so you can perform various operations with file directly so if you want to perform only one action.
By default, full read/write access to new files is granted to all users.

Syntax:

if(File.Exists("test.txt"))
{ 

}

File.Open("test.txt", FileMode.Open);
There is list of static methods to perform operation with a file.
We cannot create instance of File. Use file class typical operation with file as like creating, deleting, renaming, modifying, opening, appending, checking existence to a single file.
You can also set and get file attributes or DateTime information to the creation and access of the file. Using Directory.GetFiles and DirectoryInfo.GetFiles you can perform operation with multiple file.
Let's understand with an example:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            if (File.Exists("test.txt"))
            {
                using (BinaryReader br = new BinaryReader(File.Open("test.txt", FileMode.Open)))
                {
                    int position = 0;

                    int length = (int)br.BaseStream.Length;

                    while (position < length)
                    {
                        int a = br.ReadInt32();
                        Console.WriteLine(a);
                        position += sizeof(int);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
}

you can also visit:  www.mybook-lang.com

No comments:

Post a Comment