0% found this document useful (0 votes)
34 views8 pages

C# FileStream and StreamReader 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)
34 views8 pages

C# FileStream and StreamReader 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

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 [Link] 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 "[Link]" 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 [Link];

3. using [Link];

4. using [Link];

5. using [Link];

6. using [Link];

7.

8. namespace FileStream_CreateFile

9. {

10. class Program

11. {

12. static void Main(string[] args)

13. {

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


[Link]", [Link]);

15. [Link]();

16. [Link]("File has been created and


the Path is D:\\[Link]");

17. [Link]();

18. }

19. }

20. }
21. Output
22. File has been created and the Path is D:\\[Link]

23. _

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

OPEN [Link] AND WRITE SOME TEXT IN IT

1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7.
8. namespace AccessFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. FileStream fs = new FileStream("D:\\
[Link]", [Link]);
15. byte[] bdata=[Link]("Hello
File Handling!");
16. [Link](bdata, 0, [Link]);
17. [Link]();
18. [Link]("Successfully saved file with
data : Hello File Handling!");
19. [Link]();
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 [Link] FILE

1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
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:\\
[Link]", [Link], [Link]);
16. using (StreamReader sr = new
StreamReader(fsSource))
17. {
18. data = [Link]();
19. }
20. [Link](data);
21. [Link]();
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 [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7.
8. namespace StreamWriter_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\[Link]";
15. using (StreamWriter writer = new
StreamWriter(file))
16. {
17. [Link]("Hello");
18. [Link]("Hellow StreamWriter
Class");
19. [Link]("How are you!");
20. }
21. [Link]("Data Saved Successfully!");
22. [Link]();
23. }
24. }
25. }

Now open D:\[Link] 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 [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7.
8. namespace StreamWriter_VariableData
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\[Link]";
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. [Link]("Sum of {0} + {1} = {2}", a,
b, result);
23. }
24. [Link]("Saved");
25. [Link]();
26. }
27. }
28. }

Now open the D:\[Link] 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 [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7.
8. namespace StreamReader_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\[Link]";
15.
16. //Writer data to text file
17. using (StreamWriter writer = new
StreamWriter(file))
18. {
19. [Link]("This tutorial explains
how to use StreamReader Class in C# Programming");
20. [Link]("Good Luck!");
21. }
22.
23. //Reading text file using StreamReader Class
24. using (StreamReader reader = new
StreamReader(file))
25. {
26. [Link]([Link]());
27. }
28. [Link]();
29.
30. }
31. }
32. }

Output:

This tutorial explains how to use StreamReader Class in C#


Programming

Good Luck!

Common questions

Powered by AI

The FileStream class is a more low-level tool for file handling in C#, allowing byte-level operations to read from or write directly to files. It provides fine control over file access and sharing permissions but requires manual handling of data encoding. In contrast, the StreamWriter class is a higher-level abstraction specifically designed for writing text data, automatically handling character encoding and making it easier to write plain text to files. It is the preferred method for writing string data, due to its simplicity and usability .

In FileStream, encoding is not directly handled, as it operates at the byte level, requiring manual conversion of string data to bytes when writing and vice versa when reading. In contrast, the StreamReader class automatically handles encoding using UTF-8 as its default. This difference makes StreamReader more suitable for text data operations, while FileStream offers lower-level control suitable for byte-wise operations and custom encoding handling .

StreamWriter offers several advantages over FileStream for writing text data to files. StreamWriter simplifies text writing by automatically managing text encoding and providing methods like Write and WriteLine tailored for string data. It abstracts the complexities of converting strings to byte arrays, unlike FileStream, which requires explicit handling of data encoding. Thus, it is more convenient for tasks specifically involving text .

The FileStream class in C# is primarily used for reading from, writing to, and closing files, thus performing basic file operations within the operating system. To create a FileStream object, you need to include the System.IO namespace and instantiate a FileStream with a specified file path, FileMode, FileAccess, and FileShare enumerator. Each of these enumerators defines the manner in which the file is accessed, modified, or shared .

FileAccess controls how a file can be accessed, dictating permission levels for operations. Setting FileAccess to Read, Write, or ReadWrite determines whether the file can be read from, written to, or both. Effective use of FileAccess is crucial for enforcing security policies, reducing unauthorized file operations and minimizing unintended effects, assuring data integrity and security in applications .

The StreamReader class is used for reading text files in a specific encoding in C#, implementing a TextReader that reads characters from a byte stream. It is widely used due to its ease of implementation and default UTF-8 encoding. However, one of its limitations is that it is not thread-safe by default, which can lead to issues in multithreaded environments unless explicitly handled .

FileStream is preferred when lower-level file operations are necessary, such as when working with non-text binary files, requiring specific file access modes and sharing permissions, or when precise control over byte-level data access is needed. It is also useful when custom encoding must be applied manually or when handling file operations that are not character-based or require multi-threading capabilities beyond those provided by StreamReader or StreamWriter .

To read specific lines of text using the StreamReader class, you can iteratively call the ReadLine method inside a loop to read through the file line by line. By using conditional statements, such as if-clauses, you can skip or process specific lines based on your conditions, allowing for targeted reading. This approach offers flexibility to ignore non-relevant lines and only process those of interest .

Using the 'None' option in FileShare while opening files with FileStream means no other process or thread can access the file until the FileStream is released. This can lead to issues in a multi-user or multi-process environment where concurrent access to files is needed, potentially causing program hang or deadlock if another operation attempts to access that file during the lock period .

The FileMode enumerator defines how the operating system should open a file when creating a FileStream object. For instance, FileMode.Create specifies that a new file is created and, if it already exists, the existing file is overwritten. Whereas, FileMode.Append opens a file if it exists and sets the cursor at the end of the file for appending new data. If the file does not exist, it creates a new one. These options control file operations ensuring that actions such as overwriting or appending occur based on the developer's intent .

You might also like