Monday, 5 March 2018

027 C# File Handleing Part 1

File Handleing
A file is collection of data stored in a memory with specific name and extension. Each file have a specific name to identify a file and extension, which tells the computer , type of data  stored in it .For example a filename is "test.txt". "text" is the file name and .txt extension tells that text type data stored in this file.

                 .Net Framework used sequence of byte to read and write  file. Sequence of byte is collectively called stream. System.IO  namespace is used to file handling operation. System.IO.Stream  is an abstract class  to handle a stream of bytes. To write a file, there must be a source from which the stream will be generated and writes to the destination file. There are two type of stream input stream and output stream.  Input stream is used when reading a file  from the source  and output stream is used when writing a file to the destination.

The following is some commonly used non-abstract classes in the System.IO namespace : 

  • BinaryReader:Read primitive types as binary values .
    Example
    FileStream fs;
    fs = new FileStream("C:\\ab\\test.txt", FileMode.Open);
    BinaryReader readBinary = new BinaryReader(fs);
  • BinaryWrite: Write primitive types as binary values .
    Example
    FileStream fs;
    fs = new FileStream("C:\\ab\\test.txt", FileMode.Create);
    BinaryWriter writeBinay = new BinaryWriter(fs);
    writeBinay.Close();
  • BufferedStream:Temporary storage for a stream of bytes ,  until certain number of data stored.Both Read and Write operation can be perform.This optimize performance of network application.
    Example
    using (MemoryStream ms = new MemoryStream())
    using (BufferedStream st = new BufferedStream(st))
              {
                      for (int i = 0; i < 10000; i++)
                      {
                           st.WriteByte(6);
                      }
             }
  • Directory: Get directory structure information.
    Example
    string[] fP = Directory.GetFiles(@"c:\\ab\");
  • DirectoryInfo : directory operation can be perform.
    Example
     DirectoryInfo dirInfo = new DirectoryInfo("C:\\ab");
     string path = dirInfo.FullName;
  • DriveInfo :Helps to get drive information.
    Example 
    DriveInfo[] dr = DriveInfo.GetDrives();
    foreach (DriveInfo d in dr)
    {
          Console.WriteLine(d.Name.ToString());
    }
  • File :Use for file Operation.
    Example 
    using System;
    using System.IO;
    class Program
    {
                   static void Main()
                   {
                          string file = File.ReadAllText("C:\\ab\\text.txt");
                            Console.WriteLine(file);
                 }
    }
  • FileInfo:Used to get file information.
    Example 
    using System;
    using System.IO;
    class Program
    {
             static void Main()
              {
                  FileInfo info = new FileInfo("C:\\ab\\test.txt");
             }
    }
  • FileStream:Read and Write file from source location to destination.Move data as a stream of array bytes.
    Example
    FileStream fs;
    fs = new FileStream("C:\\ab\\test.txt", FileMode.Create);
    BinaryWriter writeBinay = new BinaryWriter(fs);
    writeBinay.Close();
  • MemoryStream:A stream of data in memory.It read and write data in memory.

    Example
    using (MemoryStream ms = new MemoryStream())
    using (BufferedStream st = new BufferedStream(st))
              {
                      for (int i = 0; i < 10000; i++)
                      {
                           st.WriteByte(6);
                      }
             }
  • IOException :When System.IO through any exception .Exception class for

    System.IO class.

    Example
    using System;
    using System.IO;
         class Program
         {
               static void Main()
                {
                   try
                       {
                            File.Open("C:\\abx\\test.txt", FileMode.Open);
                       }
                      catch (IOException ex)
                     {
                        Console.WriteLine(ex.ToString());
                        Console.ReadKey();
                   }
             }
    }


  • Path:Help to handle file path.
    Example
    using System;
    using System.IO;
    class Program
    {
              static void Main()
              {
                     string pt = "C:\\ab\\test.txt";
                      string filename = Path.GetFileName(pt);
                        string filePath = Path.GetFullPath(pt);
               }
    }
  • StreamReader: Helps to read text from byte stream.
    Example
    using System;
    using System.IO;
    class Program
    {
                static void Main()
               {
                       using (StreamReader sr = File.OpenText(@"C:\\ab\\test.txt"))
                       {
                      }
            }
    }
  • StreamWriter:Helps to write byte to text data and files.

    Example
    using System;
    using System.IO;
    class Program
    {
           static void Main()
          {
                 using (StreamWriter writer =new StreamWriter("C:\\ab\\test.txt"))
                 {
                         writer.Write("Hellow World");
                 }
            }
    }

    FileStream :
    Filestream is a class comes under system.Io. Filestream class is used for reading and writing files and also closing files. Filestream transfer data from source to destination with byte-oriented filestream wrapped with encoding. Below is the syntax of file stream class instant creation. Source filename with Path,FileModee Enumeration,FileAccess Enumeration,FileShare Enumeration,buffer size in integer.

    FileStream File_Stream_Name = new FileStream( Path,FileMode  Enumeration,FileAccess  Enumeration ,FileShare Enumeration , buffer size);
    • write : Filestream write method perform the right operation of the file. Filestream move data as a byte stream array from source to destination. A block of byte  is written in the file each time.

       Example
      using System;
      using System.IO;
          class Program
          {
                  static void Main()
                  {
                      FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Create);
                      string data = "Hellow World"; //your data
                      byte[] info = new System.Text.UTF8Encoding(true).GetBytes(data);
                      fs.Write(info, 0, info.Length);
                 }
       }

    • seek : Seek set the current position of stream to a given value.
      Example
      using System;
      using System.IO;
         class Program
         {
               static void Main()
                 {
                 long pos = 50;
                 FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Open);
                fs.Seek(pos, SeekOrigin.Begin);
                }
         }
    • readbyte : Read as byte from a file and advanced by one byte. Readbyte return integer value while  reading. It return positive value and return -1 when reach end of the file.

       Example
      using System;
      using System.IO;
         class Program
         {
                  static void Main()
                  {
                       FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Open);
                      for (int i = 0; i < fs.Length; i++)
                       {
                           Console.WriteLine(fs.ReadByte());
                      }
                     Console.ReadKey();
             }
      }
    • length :Return the length of a byte of stream. It is actually count of byte in a stream.

       Example
      using System;
      using System.IO;
             class Program
             {
                    static void Main()
                    {
                       FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Open);
                       Console.WriteLine(fs.Length);
                      Console.ReadKey();
                 }
      }
    • flush :Filestream class can be Buffered. Buffer can be clear by flash method. It also clear the intermediate buffer.

      using System;
      using System.IO;
             class Program
             {
                  static void Main()
                  {
                       FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Create);
                       string data = "Hellow World"; //your data
                       byte[] info = new System.Text.UTF8Encoding(true).GetBytes(data);
                       fs.Write(info, 0, info.Length);
                       fs.Flush();
                       Console.ReadKey();
                     }
             }


    • close :Filestream close method , close the current file stream and release all resources related to the file stream.

      using System;
      using System.IO;
               class Program
              {
                    static void Main()
                               {
                                     FileStream fs = new FileStream("C:\\ab\\test.txt", FileMode.Create);
                                     string data = "Hellow World"; //your data
                                     byte[] info = new System.Text.UTF8Encoding(true).GetBytes(data);
                                     fs.Write(info, 0, info.Length);
                                     fs.Close();
                                    Console.ReadKey();
                               }
             }


    FileMode : File mode enumeration is inbuilt enumeration in.Net framework. Here is the details of enumeration value of file mode

    • Append : Used to add  at the end of file. 

    • Create : Create a new file. If exist any file with same name and extension,  destroy the existing file and create a new file. 

    •  Create new : Create a new file. 

    • Open : Open an existing file. 

    • OpenorCreate : Open a file if exist or create if not exist.

    • Truncate : Remove all file content and set the length to zero. 

    FileAccess :FileAccess enumeration is also a inbuilt enumeration provided by the  .Net framework. Here is the list of enumeration provided by the file access. 

    • Read : open a file for reading purpose only. 

    • Write: open a file for writing. 

    • ReadWrite : open a file for reading and writing. 

     

    FileShare: FileShared is a enumerator also built ind in .Net Framework by default. 

    • None: does not allow to share file. 

    •  Read : allow share file for reading purpose only. 

    •  ReadWrite : allow share file reading and writing purpose both. 

    •  Write : allow share file for writing.  

     

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...