Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use CSharp FileStream Class



The FileStream class represents a File in the Computer. Use the FileStream class to read from, write to, open, and close files on a file system, as well as to manipulate other File related operating system handles including pipes, standard input, and standard output. FileStream allows moving data to and from the stream as arrays of bytes. We operate File using FileMode in FileStream Class

Some of FileModes as Follows :

  • FileMode.Append: Open and append to a file if the File does not exist, it creates a new file.
  • FileMode.Create: Create a new file; if the File exists, it will append to it.
  • FileMode.CreateNew : Create a new File; if the File exists, it throws an exception.
  • FileMode.Open: Open an existing file.

How to create a file using C# FileStream Class?

The following C# example shows how to create and write in a file using FileStream.

When we execute the above C# source code, it creates a new File and writes the content to the specified path.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.IO.FileStream wFile;
                byte[] byteData = null;
                byteData = Encoding.ASCII.GetBytes("FileStream Test");
                wFile = new FileStream("c:\\streamtest.txt", FileMode.Append);
                wFile.Write(byteData, 0, byteData.Length);
                wFile.Close();
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.ToString());
           }
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More