Different types of File Write Operations
Different types of File Write Operations
We saw in previous article various way to read a file. In this article, we will see the different ways to write contents to a file
The following sequence outlines the basic steps necessary to write contents to text files:
Open the file
Write to the file
Close the file
Although all these methods will achieve the same functionality more or less, there are considerable differences and hence, you should use the best method as per your requirement.
Traditional read/Write method
So let us explore the various file read methods:
Writing using File Write operations
WriteAllBytes
byte[] byt = File.ReadAllBytes(filePath);
File.WriteAllBytes(filePath, byt);
The WriteAllBytes method is actually designed to write a binary content to a file. However, it can also be used with normal text file and the byte array will be written to this file. This method will open the file (specified in the first parameter), and will replace the content of this file with byte array specified in the second parameter
WriteAllLines
WriteAllLines method writes the data from the string array into a file.
This method will open the file specified in the first parameter and will replace the content of this file with string array specified in the second parameter
string[] str = File.ReadAllLines(filePath);
File.WriteAllLines(filePath, str);
WriteAllText
WriteAllText method writes the content of the string into the file.
This method will open the file specified in the first parameter and will replace the content of this file with string specified in the second parameter
string text = File.ReadAllText(filePath);
File.WriteAllText(filePath, text);
All the above methods will replace the existing contents with the new content. However, in real time scenario, you may want to append contents to a file rather than to replace the contents of a file. For this purpose, we have to use following stream methods.
Writing using File Streams
As seen in the previous article, let us revise the basic concepts of stream classes
stream <https://msdn.microsoft.com/en-us/library/system.io.stream.aspx> is an abstract class that represents a sequence of bytes.
FileStream <https://msdn.microsoft.com/en-us/library/system.io.filestream.aspx> derives from Stream and allows you to treat a file as a Stream.
TextReader <https://msdn.microsoft.com/en-us/library/system.io.textreader.aspx>/TextWriter <https://msdn.microsoft.com/en-us/library/system.io.textwriter.aspx> are abstract classes that allow you to read/write characters.
StreamReader <https://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx>/StreamWriter <https://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx> derive from TextReader/TextWriter and provide implementations to read/write from/to a Stream (which can be a FileStream) using an Encoding <https://msdn.microsoft.com/en-us/library/system.text.encoding.aspx>.
Please choose your options appropriately based on your requirement:
For binary data, use Stream
For text data, use TextWriter/TextReader
If you start trying to read binary data with TextReader, some discrepancies or inconsistencies might happen
using StreamWriter
string filePath= "F:\tuts\kisna.txt";
// write data to text file
using (StreamWriter writer = File.CreateText(filePath))
{
// write a line of text and append a new line character
writer.WriteLine("hare krishna");
// write a string text from current position
writer.Write("hare rama");
}
Use the following statement in case you want to append text to an existing file.
using (StreamWriter writer = File.AppendText(filePath))
using TextWriter
// create writer & open file
using (TextWriter tw = new StreamWriter(filePath))
{
// write a line of text and append a new line character
tw.WriteLine("hare krishna");
// write a string text from current position
tw.Write("hare rama");
//closing a file
tw.Close();
}
Use the following statement in case you want to append text to an existing file.
Second parameter (true or false) tells whether text will be append to an existing file or not.
TextWriter tw = new StreamWriter(filePath,true)
rsp160 rsp160 rsp160 The first task above was to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, theStreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding.
1. writer.Write() - method accepts contents to append and simply append the contents at the end of the file.
2. writer.WriteLine() - method accepts contents to append and add a new line after appending contents so that next appended contents appears in the new line.
Note: This program creates a text file when it runs. In the directory mentioned in the file path, you'll find a file named kisna.txt. If you don’t specify the file path and specify only the file name then you'll find a file named kisna.txt at a location where your executable program is running (bin/debug folder for console appln). Also, File.CreateText returns a StreamWriter, which is functionally no different than manually creating a StreamWriter and using that to write to a file
rsp160 rsp160 rsp160 using FileStream
// Reading contents using FileStream
string data = "hare krishna";
// writing contents using FileStream
using (FileStream stream = File.Open(filePath, FileMode.OpenOrCreate))
{
byte[] info = new UTF8Encoding(true).GetBytes(data);
// writing data
stream.Write(info, 0, info.Length);
}
Use the following statement in case you want to append text to an existing file. Second parameter tells that we want to open the file in append text mode
using (FileStream stream = File.Open(filePath, FileMode.Append))
FileStream object gives you extra control over how you want to read or write data from / into a file. This also let you specify the mode of the file to access like in Append mode, or Create mode or only Read mode. Also you can specify Type of access you want to have as third parameter of the File.Open() method.
FileStream buffers input and output for better performance. In order to use FileStream for reading and writing, you will need to use System.Text namespace as encoding related objects like UTF8Encoding contains in this namespace.
Lastly, I would like to point out that TextReader and TextWriter are abstract base classes used by many other classes for handling different kinds of I/O operations StreamReader and StreamWriter should be used when you're actually dealing with Stream objects containing text, such as the FileStream for a text file. But a TextReader need not necessarily deal with streams; for example, take the StringReader class which also inherits from TextReader and just reads a simple string.
here
Note: Images used on this website
are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon
Foundation or were found in google search under "Free to use and share". If any
of the images presented here violates copyright issues or infringes anyone copyright
or are not under "Fair use", then please bring it to our notice. Read
Disclaimer for more.
Share this to your friends. One of your friend is
waiting for your share.
Related Articles
Ways of generating random password or string
Different types of File Read Operations
Different types of File Write Operations
Post Comment