C-sharp read write text file

In this article, we will learn how to readfile and write to a text file in .net using C-sharp. We will use FileStream, StreamWriter and StreamReader classes.

Here we will use Stream to perform read and write operation in a text file.

Before learning how to read and write files, we must be know about Stream. Stream is a sequence of bytes traveling from a source to a destination over a communication path. When we open a file for read or write modes it becomes stream.

.net System.IO library includes various classes for directories and files handling operations.

1). writing in the text file

We will use FileStream for opening a file in append mode with write permissions (FileStream will create a new file if same file will not exists.). and create StreamWriter from FileStream to write text inside file.

FileStream Class:

FileStream Class inherited from Stream class. Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

StreamWriter Class:

The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which writes a series of characters.

Following Console Application Program will create a file with name test.cs in C: drive. Write text input by user from console.

using System; using System.IO; namespace ConsoleApplication { class Program { public class FileWriter { public string FilePath { get; set; } public FileWriter(string FilePath) { this.FilePath = FilePath; } public void WriteData() { try { using (FileStream fs = new FileStream(this.FilePath, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { Console.WriteLine("Enter text for file:"); string str = Console.ReadLine(); sw.WriteLine(str); sw.Flush(); sw.Close(); fs.Close(); } } } catch (Exception ex) { Console.Write(ex.Message); } } } static void Main(string[] args) { string path = @"C:\\test.cs"; FileWriter fw = new FileWriter(path); fw.WriteData(); } } }

StreamWriter Methods:

Close: Close Method is used to close the current StreamWriter object and the underlying stream

Flush: Flush Method is used to Clears all buffers for the current writer.

Write: Write method is used to Write to the stream.

WriteLine: WriteLine method is used to Write data specified by the overloaded parameters, followed by end of line.

2) Reading a file

We will use FileStream for opening a file read only permissions and create StreamReader from FileStream to read text from file.

StreamReader Class:

The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters.

using System; using System.IO; namespace ConsoleApplication { class Program { class FileReader { public string FilePath { get; set; } public FileReader(string FilePath) { this.FilePath = FilePath; } public void ReadData() { try { using (FileStream fs = new FileStream(this.FilePath, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.WriteLine("File Contents:\n"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } Console.ReadLine(); sr.Close(); fs.Close(); } } } catch (Exception ex) { Console.WriteLine("The file could not be read:"); Console.Write(ex.Message); } } } static void Main(string[] args) { FileReader fr = new FileReader(@"D:\\test.cs"); fr.ReadData(); } } }

StreamReader Methods:

Close:

Close method is used to close the object of StreamReader class and the underlying stream, and release any system resources associated with the reader.

Peek:

Peek method is used to return the next available character but doesn't consume it.

Read:

Read method is used to read the next character or the next set of characters from the stream.

ReadLine:

ReadLine method is used to read a line of characters from the current stream and returns data as a string.

Seek:

Seek method is used to set read/write position of current pointer with in Stream, which can be moved to any position with in the file.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories