0% found this document useful (0 votes)
4 views

C# File Streams Tutorial

The document provides a comprehensive tutorial on using FileStream, StreamWriter, and StreamReader classes in C#. It explains how to create, write, and read files using these classes, along with examples of code for each operation. Key concepts such as FileMode, FileAccess, and FileShare are also discussed to help understand file handling in C#.

Uploaded by

tinozzzacky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C# File Streams Tutorial

The document provides a comprehensive tutorial on using FileStream, StreamWriter, and StreamReader classes in C#. It explains how to create, write, and read files using these classes, along with examples of code for each operation. Key concepts such as FileMode, FileAccess, and FileShare are also discussed to help understand file handling in C#.

Uploaded by

tinozzzacky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

C# Tutorial 1 File Streams

WHAT IS FILESTREAM CLASS IN C#?


FileStream Class is used to perform the basic operation of reading and writing operating system
files. FileStream class helps in reading from, writing and closing files.

HOW TO USE FILESTREAM CLASS IN C#?


In order to use FileStream class you need to include System.IO namespace and then create
FileStream Object to create a new file or open an existing file.

FileStream <object_name> = new FileStream( <file_name>,


<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare
Enumerator>);

FileMode – It specifies how to operation system should open the file. It has following members

1. Append - Open the file if exist or create a new file. If file exists then place cursor at the
end of the file.
2. Create - It specifies operating system to create a new file. If file already exists then
previous file will be overwritten.
3. CreateNew - It create a new file and If file already exists then throw IOException.
4. Open – Open existing file.
5. Open or Create – Open existing file and if file not found then create new file.
6. Truncate – Open an existing file and cut all the stored data. So the file size becomes 0.

FileAccess – It gives permission to file whether it will


open Read, ReadWrite or Write mode. FileShare – It opens file with following share
permission.

1. Delete – Allows subsequent deleting of a file.


2. Inheritable – It passes inheritance to child process.
3. None – It declines sharing of the current files.
4. Read- It allows subsequent opening of the file for reading.
5. ReadWrite – It allows subsequent opening of the file for reading or writing.
6. Write – Allows subsequent opening of the file for writing.

In this programming Example we will create a new file "CsharpFile.txt" and saves it on disk.
And then we will open this file, saves some text in it and then close this file.
CREATE A BLANK .TXT FILE USING FILESTREAM

1. using System;

2. using System.Collections.Generic;

3. using System.Linq;

4. using System.Text;

5. using System.Threading.Tasks;

6. using System.IO;

7.

8. namespace FileStream_CreateFile

9. {

10. class Program

11. {

12. static void Main(string[] args)

13. {

14. FileStream fs = new FileStream("D:\\


csharpfile.txt", FileMode.Create);

15. fs.Close();

16. Console.Write("File has been created and


the Path is D:\\csharpfile.txt");

17. Console.ReadKey();

18. }

19. }

20. }
21. Output
22. File has been created and the Path is D:\\csharpfile.txt

23. _

Explanation:
In the above program I added System.IO namespace so that I could use FileStream class in my
program. Then I created an object of FileStream class fs to create a
new csharpfile.txt in D drive.

OPEN CSHARPFILE.TXT AND WRITE SOME TEXT IN IT

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace AccessFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. FileStream fs = new FileStream("D:\\
csharpfile.txt", FileMode.Append);
15. byte[] bdata=Encoding.Default.GetBytes("Hello
File Handling!");
16. fs.Write(bdata, 0, bdata.Length);
17. fs.Close();
18. Console.WriteLine("Successfully saved file with
data : Hello File Handling!");
19. Console.ReadKey();
20. }
21. }
22. }

Output

Successfully saved file with data : Hello File Handling!


_

Explanation
In the above program again I created object as fs of FileStrem class. Then Encoded a string
into bytes and kept into byte[] variable bdata and finally using Write() method of
FileStream stored string into file.

READ DATA FROM CSHARPFILE.TXT FILE

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileStream_ReadFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string data;
15. FileStream fsSource = new FileStream("D:\\
csharpfile.txt", FileMode.Open, FileAccess.Read);
16. using (StreamReader sr = new
StreamReader(fsSource))
17. {
18. data = sr.ReadToEnd();
19. }
20. Console.WriteLine(data);
21. Console.ReadLine();
22. }
23. }
24. }

Output

Hello File Handling!

_
Explanation
In the above example I opened file in a Read permission and use StreamReader class to read
file.

WHAT IS STREAMWRITER CLASS?


StreamWriter Class is more popular in File Handling and it is very helpful in writing text data
in the file. It is easy to use and provides a complete set of constructors and methods to work.

HOW TO WRITE TEXT INTO A FILE USING STREAMWRITER CLASS?


It is very easy to writer data into a text file using StreamWriter Class and most of the beginners
prefer to use this class in writing file. You can understand it with the following programming
example.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StreamWriter_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15. using (StreamWriter writer = new
StreamWriter(file))
16. {
17. writer.Write("Hello");
18. writer.WriteLine("Hellow StreamWriter
Class");
19. writer.WriteLine("How are you!");
20. }
21. Console.WriteLine("Data Saved Successfully!");
22. Console.ReadKey();
23. }
24. }
25. }

Now open D:\csharpfile.txt and you will see data is saved.

SAVE VARIABLE DATA TO FILE


Several times you need to save variable data in a file. These variable data might be the output of
your program, log details, exception error etc. In the next programming, I will show you how can
you save variable data in a file using StreamWriter Class.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StreamWriter_VariableData
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15. int a, b, result;
16. a = 5;
17. b = 10;
18. result = a + b;
19.
20. using (StreamWriter writer = new
StreamWriter(file))
21. {
22. writer.Write("Sum of {0} + {1} = {2}", a,
b, result);
23. }
24. Console.WriteLine("Saved");
25. Console.ReadKey();
26. }
27. }
28. }

Now open the D:\csharpfile.txt again and you will see the following text in a file.
Sum of 5 + 10 = 15

WHAT IS STREAMREADER CLASS?


StreamReader class allows you to read text files easily. Its implementation is easy and it is
widely popular among the programmer. However, there are dozens of way to read text file in C#
file handling but StreamReader Class is more popular in list.
Important Points about StreamReader Class

1. Implements a TextReader that reads characters from a byte stream in a particular


encoding.
2. StreamReader class uses UTF-8 Encoding by defaults.
3. StreamReader class is designed for character input in a particular encoding.
4. Use this class for reading standard text file.
5. By default, it is not thread safe.

HOW TO READ FILE USING STREAMREADER CLASS?


As mentioned above it is very easy to read text file using StreamReader Class. Here I am going
to write a program that does following thing:

1. Write some data on text file using StreamWriter class and


2. Read those data using StreamReader class.

PROGRAMMING EXAMPLES AND CODE

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace StreamReader_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharpfile.txt";
15.
16. //Writer data to text file
17. using (StreamWriter writer = new
StreamWriter(file))
18. {
19. writer.WriteLine("This tutorial explains
how to use StreamReader Class in C# Programming");
20. writer.WriteLine("Good Luck!");
21. }
22.
23. //Reading text file using StreamReader Class
24. using (StreamReader reader = new
StreamReader(file))
25. {
26. Console.WriteLine(reader.ReadToEnd());
27. }
28. Console.ReadKey();
29.
30. }
31. }
32. }

Output:

This tutorial explains how to use StreamReader Class in C#


Programming

Good Luck!

You might also like