FileStream - DotNet and DataBase

Wednesday, 25 July 2018

FileStream



FileStream objects are used to read data from the files and write/append data into the files.
Using file objects we can read data from the files like .txt,.word etc.. and we can appnd data into the files. File objects are derived from the base class "using System.IO;"

Using file objects we can do different activities like create,delete,read and write etc..

Let us see now how to create a text file using file object. I have a folder (Create) in C: drive and I want to create a file "Text.txt", my code is as follows.

using System;
using System.IO;
public class FileStreamExample
{
    public static void Main(string[] args)

    {
        FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    }
}


FileMode: FileMode class has different methods like "Append,Create,CreateNew,Open,OpenOrCreate"

Append: Open the file if exist or create a new file. If file exists then place cursor at the end of the file.
Example:
using System;
using System.IO;
using System.Text;

public class FileStreamExample
{
    public static void Main(string[] args)
    {
        FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.Append);
        byte[] buffer = Encoding.Default.GetBytes("Hello World!");
        fs.Write(buffer, 0, buffer.Length);
        fs.Close();
    }
}

Create : Creates a new file on the specified path. If the file already exists in the supplied location, overrides the file.
Example
public class FileStreamExample
{
    public static void Main(string[] args)
    {
        FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.Create);    }
}


CreateNew: Creates a new file on the specified path. If the file already exists in the supplied location, throws error.
public class FileStreamExample
{
    public static void Main(string[] args)
    {
        FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.CreateNew);    }
}

Open: Opens the file from the supplied location
FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.Open,FileAccess.Read);

OpenOrCreate: Opens the file from the supplied location, if it not exists in the supplied location creates the file.
FileStream fs = new FileStream(@"C:\Create\Text.txt", FileMode.OpenOrCreate,FileAccess.Read);

FileAccess: FileAccess class has different methods like "" which provides different permissions like "Read,ReadWrite,Write"

Read: Allows users to read the file. Doesn't allow to write.
ReadWrite: Allows users to read  and write the file
Write: Allows users to write only.

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.