Write to a File With OpenWrite Using C#

Introduction

The OpenWrite method opens a file for writing. If the file does not exist, it creates a new file and opens it for writing. The OpenWrite method takes a file name as a parameter and returns a FileStream object on the specified file.

FileStreamfs=File.OpenWrite(fileName);

With the FileStream object, we can use its Write method to write to the file. The WriteMethod takes a byte array. The following code snippet creates a byte array and passes it to the Write method of the FileStream.

byte[] info = new UTF8Encoding(true).GetBytes("NewFileusingOpenWriteMethod\n");
fs.Write(info, 0, info.Length);

string fileName = @"C:\Temp\FOWM.txt";

try
{
    using (FileStream fs = File.OpenWrite(fileName))
    {
        info = new UTF8Encoding(true).GetBytes("NewFileusingOpenWriteMethod\n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("----------START------------------------\n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("Author: Mahesh Chand\n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("Book: ADO.NET Programming using C#\n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("----------END------------------------");
        fs.Write(info, 0, info.Length);
    }

    using (FileStream fs = File.OpenRead(fileName))
    {
        byte[] byteArray = new byte[1024];
        UTF8Encoding fileContent = new UTF8Encoding(true);
        while (fs.Read(byteArray, 0, byteArray.Length) > 0)
        {
            Console.WriteLine(fileContent.GetString(byteArray));
        }
    }
}
catch (Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}

File.Open Method

Opens a FileStream on the specified path.

FileStream Class

This method Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
publicclassFileStream:System.IO.Stream

Example

The following example demonstrates some of the FileStream constructors in C#.

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MySample.txt";

        if (File.Exists(path))
        {
            File.Delete(path);
        }

        using (FileStream fs = File.Create(path))
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i = 1; i < 120; i++)
            {
                AddText(fs, Convert.ToChar(i).ToString());
            }
        }

        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b, 0, b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }

    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}

This example shows how to write to a file asynchronously.

This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer.

Example

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            UnicodeEncoding uniencoding = new UnicodeEncoding();
            string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";
            byte[] result = uniencoding.GetBytes(UserInput.Text);

            using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
            {
                SourceStream.Seek(0, SeekOrigin.End);
                await SourceStream.WriteAsync(result, 0, result.Length);
            }
        }
    }
}

The Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations.

Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. FileStream buffers input and output for better performance In C#.

Note. This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface in this topic.

The IsAsync property detects whether the filehandle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously in c#.

The Seek method supports random access to files. Seek allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration in c#.

Note. This method used the Disk files to always support random access. At the time of construction, the CanSeek property value is set to true or false depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in win base.h, the CanSeek property value is true. Otherwise, the CanSeek property value is false.

If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

For directory operations and other file operations, see the File, Directory, and Path classes. The File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and is similar to the FileStream class.

For a list of common file and directory operations, see Common I/O Tasks.

Detection of Stream Position Changes

This method used a FileStream object that does not have an exclusive hold on its handle, another thread could access the filehandle concurrently and change the position of the operating system's file pointer that is associated with the filehandle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the FileStream object.

If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

If an unexpected change in the handle position is detected in a call to the write method, the contents of the buffer are discarded and an IOException exception is thrown.

A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

Summary

In this article, we learned about how to write to a file with OpenWrite Using C#.


Similar Articles