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.  

     

028 C# Reflection

Reflection
When .Net program is compiled , MSIL create a metedeta file , named manifest. Portable executable file or (PE)  store metadata + manifest information of  assembly. This can be access run time. This process is called reflection. PE  is generated when program is compiled in CLR. 

Portable executable file or (PE) has three part. 
  • PE header 
  • entry point 
  • code metadata
 In a nutshell, reflection is used to get type information during runtime. Reflection comes under the namespace System.Reflection.System.Reflection contain the class to retrieve the type information of existing object and dynamically added object. To retrieve the type information of an object, you need to create a instance of that type and binding it to the existing object.
Gettype() is the method to obtain the type information. Here is the list of type of information con be obtain from System.Reflection.
  • Module
  • Enum
  • MethodInfo
  • ConstructorInfo
  • MemberInfo
  • ParameterInfo
  • Type
  • FieldInfo
  • EventInfo
  • PropertyInfo 
  • Attributes
  • Enum
  • Event
  • Fields
Below is the example of  of how get type work

Example 1

using System;
namespace Application
{
       class school
      {

       }

      class Student
      {
            public static void Main()
            {
                  school obj = new school();
                 // Get the Type information.
                   Type objType = obj.GetType();
                 Console.WriteLine(objType.ToString());
                 Console.ReadKey();
            }
      }

}

Output





Below is the example how get information from reflection by creating instance of an existing class. The example shows how method information can be obtain and invoke method with argument. The example also so how property information can be obtained.

Example 1

using System;
using System.Reflection;

namespace Application
{
    class school
    {
       public int Id
        {
          get; set;
       }
      public void Getfees(int Param1 , string Param2)
      {
        Console.WriteLine("Value of Param1:" + Param1);
        Console.WriteLine("Value of Param2:" + Param2);
       }
}

class Student
{
          public static void Main()
          {
             school obj = new school();
            // Get the Type information.

             Type objType = obj.GetType();
             Console.WriteLine(objType.ToString());

             Console.WriteLine("*********************Method Information*************************");
             //Method Information
             MethodInfo myMethodInfo = objType.GetMethod("Getfees");

              //Method Name
              Console.WriteLine("Method Name :" +myMethodInfo.Name);

               //Method Attributes
                Console.WriteLine("Method Attributes :" + myMethodInfo.Attributes);

                //Method Invoke
                object[] arr = new object[] { 2, "Hellow World" };
                myMethodInfo.Invoke(obj, arr);

                 Console.WriteLine("********************Property Information********************");
                 //Get Property information
                 PropertyInfo[] propInfo = objType.GetProperties();

                 foreach (PropertyInfo pobj in propInfo)
                     {
                          Console.WriteLine(pobj.Name);
                     }

         Console.ReadKey();

                  }

           }

}

Output


 


Assembly 
System.Reflection.Assembly class  help us to load and define assembly and get information like assembly name, version, location ,versionable. Assembly class can read the manifest during run time. Below is the example how an assembly class can be used.

using System;
using System.Reflection;
namespace Application
{

class Student
{
         public static void Main()
         {
             var assembly = Assembly.GetExecutingAssembly();
             Console.WriteLine("Assembly Name: " + assembly.GetName().Name);
             Console.WriteLine("Version: " + assembly.GetName().Version.ToString());
             Console.WriteLine("Full Name of Assembly"+assembly.FullName.ToString());
             Console.WriteLine("Location of Assembly" + assembly.Location.ToString());
            Console.ReadKey();
         }
   }

}

Output :


Dynamically Create Instance of a Class at Runtime in C#

Reflection support activated create instance to create dynamic instance of a class. Below is the example of dynamically created  of  class.
using System;
using System.Reflection;

namespace Application
{
            class school
            {
              public void ShowData(string param1,string param2)
                {
                    Console.WriteLine(param1 + " " + param2);
                }
            }

            class Student
            {

                public static void Main()
                 {
                    Object obj = Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase,
                                                                                                            typeof(school).FullName);

                    Console.ReadKey();
                   }
            }
}

We can load dll or assembly file with the full path and the get assembly information. File will be loaded to assembly variable and you can use it .Belows the example of the same 

 
using System;
using System.Reflection;

namespace Application
{
                class school
                 {
                      public void ShowData(string param1,string param2)
                       {
                         Console.WriteLine(param1 + " " + param2);
                       }
                   }

                  class Student
                  {
                    public static void Main()
                      {
                                Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection   \reflection.dll");
                                Console.ReadKey();

                      }
}

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

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