Home » C# programs » C# FileStream class programs

C# program to demonstrate the use of FileStream class

In this article, we will learn about FileStream class. Here we will open a file with given mode and then provide access to file.
Submitted by IncludeHelp, on November 17, 2017

File Modes

Here, FileMode is an enum that contains following items.

  1. FileMode.Open
    This mode specifies that we can open an existing file.
  2. FileMode.OpenOrCreate
    This mode specifies that we can open an existing file. If file does not exist then it creates new file.
  3. FileMode.Create
    This mode specifies that we create a new file. If file already exists then it overwrites old file.
  4. FileMode.CreateNew
    This mode specifies that we create a new file. If file already exists then it thrown an exception.
  5. FileMode.Append
    This mode specifies that Open a file and seeks to the end of file. If file does not exist then it creates new file.
  6. FileMode.Truncate
    This mode specifies that open a existing file, then truncate that file.

File Access

Here, FileAccess is an enum that contains following items

  1. FileAccess.Read
    Provide read access of file.
  2. FileAccess.Write
    Provide write access of file.
  3. FileAccess.ReadWrite
    Provide read and write both access of file.

Example:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            byte b1 = 10;
            byte b2 = 0;

            FileStream f1;
            FileStream f2;

            f1 = new FileStream("abc.txt", FileMode.Create, FileAccess.Write);

            f1.WriteByte(b1);
            f1.Close();

            f2 = new FileStream("abc.txt", FileMode.Open, FileAccess.Read);
            
            b2 = (byte)f2.ReadByte();
            Console.WriteLine("Val : " + b2);
            f2.Close();
        }
    }
}

Output

Val : 10

In above program, we need to remember, when we use "FileStream" class then we need to include System.IO namespace in the program.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.