type or namespace name "StreamReader" could not be found

12,655

Solution 1

StreamReader is in the System.IO namespace. You can add this namespace at the top of your code by doing the following-

using System.IO;

Alternatively, you could fully qualify all instances of StreamReader like so-

System.IO.StreamReader sr = new System.IO.StreamReader(filename);

But this may get a little tedious, especially if you end up using other objects in System.IO. Therefore I would recommend going with the former.

More on namespaces and the using directive-

https://msdn.microsoft.com/en-us/library/0d941h9d.aspx

https://msdn.microsoft.com/en-us/library/sf0df423.aspx

Solution 2

StreamReader requires a namespace which you are missing. Add these two at top of the .cs file.

using System;
using System.IO;
StreamReader sr = new StreamReader(filename);

Its always a best-practice to add namespace at top of the file. However, you can add like this System.IO.StreamReader mentioned by @iliketocode.

System.IO.StreamReader sr = new System.IO.StreamReader(filename);

Solution 3

I wasn't going to post the answer, but just had another good programming practice to point out.

Firstly, to answer your question, if you want to use StreamReader you need to tell the compiler where to find it. Adding a using System.IO.StreamReader; at the top of your .cs file would do that.

Secondly, when using streams, it is better to wrap your interaction with the stream in a using(){}. The way I would write your code would be:

using System;
using System.IO;
using System.IO.StreamReader;

class Perfect
{
    static void Main()
    {
        const string filename = @"marks.cvs";
        using (var sr = new StreamReader(filename))
        {
            string line = sr.ReadLine();
            Console.WriteLine(line);
        }
    }
}
Share:
12,655
maddddie123
Author by

maddddie123

Updated on August 13, 2022

Comments

  • maddddie123
    maddddie123 almost 2 years

    I am working on StreamReader in C#. I am getting the error

    "The type or namespace name "StreamReader" could not be found"

    I have no idea what I am doing wrong.

    using System.IO;
    using System;
    class Perfect
    {
    static void Main()
        {
        string filename = @"marks.cvs";
        StreamReader sr = new StreamReader(filename);
        string line = sr.ReadLine();
        Console.WriteLine(line);    
        sr.Close();
        }
    }