Gt_R
Gt_R

Reputation: 225

Files: Filestream and StreamWriter Wrapper Class

I have a confusion here in understanding the relationship between object fs and object sw in the following line of code.

StreamWriter sw = new StreamWriter(fs);

The confusion is in understanding whether,

1> Is sw just pointing to the object fs 2> when fs is passed as parameter to StreamWriter constructor which members are initialized to the contents of object fs.

Please explain the mechanism in detail how FileStream class and StreamWriter class are accomplishing the task through object references fs and sw.

     using System;

     using System.IO;

     class File_Write
        {
           public void Write_Data()
            {

                int empid = 12;
                string empname = "sean";



            FileStream fs = new FileStream("E:\\Files_Demo\\File_Write.txt", FileMode.Create,
                FileAccess.Write, FileShare.None);

            StreamWriter sw = new StreamWriter(fs)
            {
                sw.WriteLine("Good Morning");
                sw.WriteLine("Provide_EmployeeDetails");

                sw.WriteLine("Employee Id={0}", empid);


                Console.WriteLine("Written to file...Success");
                Console.Read();


            }
      }

Upvotes: 2

Views: 1142

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292615

A Stream is just a sequence of bytes that you can read, write, and/or seek (depending on the type of stream). It's just raw binary data, with no knowledge of what the data means and how to process it.

A StreamWriter is used to write text on a stream, using the specified text encoding (UTF-8 by default). Writing text directly on a Stream without using a StreamWriter is possible, but not very convenient (you would need to manually convert the string to bytes)

Similarly, a StreamReader is used to read text from a Stream.

1> Is sw just pointing to the object fs

It holds a reference to it, yes.

2> when fs is passed as parameter to StreamWriter constructor which members are initialized to the contents of object fs.

fs doesn't have a content; it's just a way to access the underlying data (in this case, a file on disk). So StreamWriter isn't "initialized to the content of object fs"; it just stores a reference to fs so that it can manipulate it later.

Upvotes: 3

Related Questions