reading text file with streamreader in object

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
I try to read a text file in an object but I get error message that I don't understand please help me. I need to do this homework.
the error msg is
Severity Code Description Project File Line Suppression State
Error CS1955 Non-invocable member 'StreamReader' cannot be used like a method. metjelentes C:\Users\Dell\source\repos\metjelentes\metjelentes\Program.cs 21 Active
the error appears at the line using(...


monthly weathercast:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace metjelentes
{
    class adatok
    {
        public string telepules = " ";
        public string ido = " ";
        public string szeliranyes_erosseg = " ";
        public int homerseklet = 0;
    }
    class beolvasas
    {       
        public void beolvas()
         {
            string olvas = @"c:\Users\Public\textfiles\tavirathu13.txt";
            using (StreamReader sr = StreamReader(olvas, Encoding.Default))
                {
                    //StreamReader sr = new StreamReader(olvas, Encoding.Default);
                    List<adatok> lista = new List<adatok>();
          
                    while (!sr.EndOfStream)
                        {
                            string sor = sr.ReadLine();
                            string[] elemek = sor.Split(' ');
                            lista.Add(new adatok());

                        }
                }
          }
     }
        class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,265
Location
Norway
Programming Experience
10+
new StreamReader(...)
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,265
Location
Norway
Programming Experience
10+
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
thank you for help. I've checked w3schools constructors. it is to initialize an object, I don't understand my experiment, why do I get error msg?
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,265
Location
Norway
Programming Experience
10+
You have to change the code to use constructor like I've shown you.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,025
Location
Chesapeake, VA
Programming Experience
10+
I hope here is a more legible explanation of what is going wrong:

Let's say we have a Car class which takes a string as a constructor:
C#:
class Car
{
    public Car(string model)
    {
    }
}

Your code is trying instantiate a Car by doing this:
C#:
Car tesla = Car("Tesla");
You are trying to call the constructor like a method.

You should have been doing this instead:
C#:
Car tesla = new Car("Tesla");
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,025
Location
Chesapeake, VA
Programming Experience
10+
What book or tutorial are you using to learn C#? I think you should consider switching to a different one because it feels like for the past few threads you've been hitting some problems where a good book or tutorial would have taught you the language fundamentals, and that the error messages have been clear about stating what is wrong -- assuming that you had the fundamentals. Yes, I know that there are some C# errors that can get pretty esoteric, but so far you've not yet hit those.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,187
Location
Sydney, Australia
Programming Experience
10+
Apart from anything else, all you had to do was look at your own code. You obviously know how to create an object because you're doing it here:
C#:
List<adatok> lista = new List<adatok>();
You're trying to create an object and failing on the line generating the error:
C#:
StreamReader sr = StreamReader(olvas, Encoding.Default)
The difference between those two lines should be fairly obvious, especially when @JohnH pointed it out specifically.

You need to be more methodical in your approach. Sure, the first step is to just look at the code in question and see if anything jumps out. If that doesn't help though, stop looking at the code because you're obviously seeing what you expect to see rather than what's actually there. Ask yourself what exactly it is that you are trying to achieve. Once you know that, go elsewhere and work out how to do that. Once you know how to do what you want to do, go back to your code and see whether that's what you're actually doing. If you had done that then the answer to the question would have been that you want to create a new StreamReader object and you obviously know how to create a new object so when you went back to your code you would see that it was not doing what is required to create a new object. Learning to think this way is part of becoming a better developer.
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
Apart from anything else, all you had to do was look at your own code. You obviously know how to create an object because you're doing it here:
C#:
List<adatok> lista = new List<adatok>();
You're trying to create an object and failing on the line generating the error:
C#:
StreamReader sr = StreamReader(olvas, Encoding.Default)
The difference between those two lines should be fairly obvious, especially when @JohnH pointed it out specifically.

You need to be more methodical in your approach. Sure, the first step is to just look at the code in question and see if anything jumps out. If that doesn't help though, stop looking at the code because you're obviously seeing what you expect to see rather than what's actually there. Ask yourself what exactly it is that you are trying to achieve. Once you know that, go elsewhere and work out how to do that. Once you know how to do what you want to do, go back to your code and see whether that's what you're actually doing. If you had done that then the answer to the question would have been that you want to create a new StreamReader object and you obviously know how to create a new object so when you went back to your code you would see that it was not doing what is required to create a new object. Learning to think this way is part of becoming a better developer.
thank you for help. my problem is that I have an instance from the school that I try use in my way but something is wrong. also I tried w3schools. I try to declare a class for record 'pattern' then based on it load a txt file in a record list as I did before without object oriented programming. as I understood the school example is missing the record part and I try to make my own version, please help me. thank you., frank.
the school example:
weather cast main:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace OpeningWeekend1
{
    class Beolvasas
    {
        List<Filmek> lista = new List<Filmek>();
        static int db = 0;

        public void beolvas()
        {
            using (StreamReader sr = new StreamReader("nyitohetvege.txt", Encoding.UTF8))
            {
                sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    string[] sor = sr.ReadLine().Split(';');
                    Filmek f = new Filmek();
                    f.eredcim = sor[0];
                    f.magycim = sor[1];
                    f.bemutato = sor[2];
                    f.forgalmazo = sor[3];
                    f.bevetel = Int32.Parse(sor[4]);
                    f.latogato = Int32.Parse(sor[5]);
                    lista.Add(f);
                    db++;

                }
            }
            Console.WriteLine("Beolvasás kész");
        }

        public void filmek()
        {
            Console.WriteLine("3. feladat: Filmek száma az állományban: {0} db", db);
        }

        public void bevetel()
        {
            double bevetel = 0;
            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].forgalmazo == "UIP")
                {
                    bevetel += lista[i].bevetel;
                }
            }
            Console.WriteLine("4. feladat: UIP Duna Flm 1. hetes bevételének összege: {0:c0}", bevetel);
        }
        public void legtobblatogato()
        {
            int legtobb = 0;
            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].latogato > lista[legtobb].latogato)
                {
                    legtobb = i;
                }
            }
            Console.WriteLine("5.feladat: A legtöbb látogató az első héten:\n\t\tEredeti cím: {0}\n\t\tMagyar cím: {1}\n\t\tForgalmazó: {2}\n\t\tBevétel: {3:c0}\n\t\tLátogató: {4}", lista[legtobb].eredcim, lista[legtobb].magycim, lista[legtobb].forgalmazo, lista[legtobb].bevetel, lista[legtobb].latogato);
        }
        public void vanew()
        {
            string cmagyar = "";
            string cangol = "";
            bool ertek = false;
            bool ertek2 = false;
            for (int i = 0; i < lista.Count; i++)
            {
                cangol = lista[i].eredcim.TrimEnd();
                string[] valami = cangol.Split();
                for (int j = 0; j < valami.Length; j++)
                {
                    if (valami[j][0] == 'W' || valami[j][0] == 'w')
                    {
                        ertek = true;
                    }
                }
                cmagyar = lista[i].magycim.TrimEnd();
                string[] valami2 = cmagyar.Split();
                for (int j = 0; j < valami2.Length; j++)
                {
                    if (valami2[j][0] == 'W' || valami2[j][0] == 'w')
                    {
                        ertek2 = true;
                    }
                }

            }
            if (ertek && ertek2)
            {
                Console.WriteLine("6. feladat: Van ilyen film");
            }
            else
            {
                Console.WriteLine("6. feladat:Nincs ilyen film");
            }
        }
        public void csv()
        {
            List<string> forgalmazo = new List<string>();
            StreamWriter sw = new StreamWriter("stat.txt");
            sw.WriteLine("forgalmazo;filmekSzama");
            for (int i = 0; i < lista.Count; i++)
            {
                if (!forgalmazo.Contains(lista[i].forgalmazo))
                {
                    forgalmazo.Add(lista[i].forgalmazo);
                }
            }
            for (int i = 0; i < forgalmazo.Count; i++)
            {
                int darab = 0;
                for (int j = 0; j < lista.Count; j++)
                {
                    if (forgalmazo[i] == lista[j].forgalmazo)
                    {
                        darab++;
                    }
                }
                if (darab > 1)
                {
                    sw.WriteLine(forgalmazo[i] + ";" + darab);
                }
            }
            sw.Close();
        }
        public void intercom()
        {
            DateTime d1;
            DateTime d2;
            double kul = 0;
            double valami = 0;
            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].forgalmazo == "InterCom")
                {
                    d1 = Convert.ToDateTime(lista[i].bemutato);
                    for (int j = i + 1; j < lista.Count; j++)
                    {
                        if (lista[j].forgalmazo == "InterCom")
                        {
                            d2 = Convert.ToDateTime(lista[j].bemutato);
                            TimeSpan ts = d2.Subtract(d1);
                            kul = ts.TotalDays;
                            i = j;
                            j = lista.Count;
                            if (valami < kul)
                            {
                                valami = kul;
                            }
                        }
                    }
                }
            }
            Console.WriteLine("6. feladat: A leghosszabb időszak két InterCom-os film között: " + valami + " nap");
        }

    }
}
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
What book or tutorial are you using to learn C#? I think you should consider switching to a different one because it feels like for the past few threads you've been hitting some problems where a good book or tutorial would have taught you the language fundamentals, and that the error messages have been clear about stating what is wrong -- assuming that you had the fundamentals. Yes, I know that there are some C# errors that can get pretty esoteric, but so far you've not yet hit those.
I've used a bit w3schools. I am taking a programming course but this covid thing forced us online. the problem is that one of our courses started 30 min earlier and I missed the object oriented 'explanation'. checking w3schools still doesn't help enough in the matter. please help me, thank you.
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
I've used a bit w3schools. I am taking a programming course but this covid thing forced us online. the problem is that one of our courses started 30 min earlier and I missed the object oriented 'explanation'. checking w3schools still doesn't help enough in the matter. please help me, thank you
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
thank you for help. I managed to fix the problem but I've got another one. I tried to use record list from its own class to be accessible from other classes. something went wrong, as I try use it in class beolvas() (read in), the access mode of my record list causes error. can I get help?
weather cast:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace metjelentes
{
    class adatok
    {
        public string telepules = " ";
        public string ido = " ";
        public string szeliranyes_erosseg = " ";
        public int homerseklet = 0;
    }
    class adatlista
    {
        public List<adatok> lista = new List<adatok>();
    }
        class beolvasas
    {       
        public void beolvas()
         {
            string olvas = @"c:\Users\Public\textfiles\tavirathu13.txt";
            using (StreamReader sr =new StreamReader(olvas, Encoding.Default))
                {
                //StreamReader sr = new StreamReader(olvas, Encoding.Default);

                //List<adatok> lista = new List<adatok>();
                int db = 0;
                    while (!sr.EndOfStream)
                        {
                            string sor = sr.ReadLine();
                            string[] elemek = sor.Split(' ');
                            adatlista.lista.Add(new adatok());
                            adatlista.lista[db].telepules=elemek[0];
                            adatlista.lista[db].ido = elemek[1];
                            adatlista.lista[db].szeliranyes_erosseg = elemek[2];
                            adatlista.lista[db].homerseklet = Int32.Parse(elemek[3]);
                            db++;
                        }
                Random rd = new Random();
                int rand_num = rd.Next(1, db);
            }
          }
     }
    /*
    class felhasznalo
    {
        foreach (string elem  beolvas.lista[])

    }*/
       class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
        }
}
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,025
Location
Chesapeake, VA
Programming Experience
10+
On line 18 you declared lista as a result instance variable. On lines 35-39 you are trying to access it as it were a class variable. That won't work. You need to first create an instance of adatlista
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
On line 18 you declared lista as a result instance variable. On lines 35-39 you are trying to access it as it were a class variable. That won't work. You need to first create an instance of adatlista
thank you for help. I tried my best but still I need help, please have a look
weather cast:
 int db = 0;
                    while (!sr.EndOfStream)
                        {
                            string sor = sr.ReadLine();
                            string[] elemek = sor.Split(' ');
                            adatlista rekordok = new adatlista();
                            rekordok.Add(new adatlista());
                            rekordok.lista[db].telepules=elemek[0];
                            rekordok.lista[db].ido = elemek[1];
                            rekordok.lista[db].szeliranyes_erosseg = elemek[2];
                            rekordok.lista[db].homerseklet = Int32.Parse(elemek[3]);
                            db++;
                        }
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,025
Location
Chesapeake, VA
Programming Experience
10+
It would help you tell us what error you are getting now.

Off the top of my head, it looks like you are creating a new instance of adatlista for each line that you find in your file. Probably not what you want to do. You probably want to create one instance and then keep adding to the list in that instance.
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
It would help you tell us what error you are getting now.

Off the top of my head, it looks like you are creating a new instance of adatlista for each line that you find in your file. Probably not what you want to do. You probably want to create one instance and then keep adding to the list in that instance.
thank you for help. the idea is to have record class and record list class separate to access it from different objects. one object is olvas( read) where I read data from text file, another would be another object with other task. so I think an instance would be the way to access the record list from different objects . obviously have to be filled up from olvas( read) to be useable for farther process. thank you
weather cast:
while (!sr.EndOfStream)
                        {
                            string sor = sr.ReadLine();
                            string[] elemek = sor.Split(' ');
                            adatlista adat = new adatlista();
                            adat.lista.Add(new adatok());
                            adat.lista[db].telepules=elemek[0];
                            adat.lista[db].ido = elemek[1];
                            adat.lista[db].szeliranyes_erosseg = elemek[2];
                            adat.lista[db].homerseklet = Int32.Parse(elemek[3]);
                            db++;
                        }
the error
(1,1): error CS0246: The type or namespace name 'adatlista' could not be found (are you missing a using directive or an assembly reference?)
(2,29): error CS0246: The type or namespace name 'adatlista' could not be found (are you missing a using directive or an assembly reference?)
(2,47): error CS0246: The type or namespace name 'adatok' could not be found (are you missing a using directive or an assembly reference?)
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
also I need to access the record list class so the created instance filled up previously in olvas(read) class
class felhasznalo
{
adatlista adat = new adatlista();
foreach (string elem in adat.lista)
{

}
}
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,025
Location
Chesapeake, VA
Programming Experience
10+
If you need the list for later on, then why do you keep on creating a brand new object that holds the list on line 5 of your code in post #17. It's still the same problem as I described in post #16.

As for the errors you are getting, please post your complete code. The first error you are getting is referring to line 1, but it doesn't make sense since based on the code you presented in post #13, line one is using System; would have not even have the identifier adatlista for the compiler to complain about. Then the following two errors don't quite make sense since according to pest #13, you declared those two classes within the same namespace, yet the compiler can't find them. The only thing I can think of is that you are not showing us your complete code, nor the code within the context that it lives within.
 

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
If you need the list for later on, then why do you keep on creating a brand new object that holds the list on line 5 of your code in post #17. It's still the same problem as I described in post #16.

As for the errors you are getting, please post your complete code. The first error you are getting is referring to line 1, but it doesn't make sense since based on the code you presented in post #13, line one is using System; would have not even have the identifier adatlista for the compiler to complain about. Then the following two errors don't quite make sense since according to pest #13, you declared those two classes within the same namespace, yet the compiler can't find them. The only thing I can think of is that you are not showing us your complete code, nor the code within the context that it lives within.
thank you for help. my code is the following
weather cast:
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace metjelentes
{
    class adatok
    {
        public string telepules = " ";
        public string ido = " ";
        public string szeliranyes_erosseg = " ";
        public int homerseklet = 0;
    }
    class adatlista
    {
        public List<adatok> lista = new List<adatok>();
    }

    class beolvasas
     {      
        public void beolvas()
         {
            string olvas = @"c:\Users\Public\textfiles\tavirathu13.txt";
            using (StreamReader sr =new StreamReader(olvas, Encoding.Default))
                {
                //StreamReader sr = new StreamReader(olvas, Encoding.Default);

                //List<adatok> lista = new List<adatok>();
                int db = 0;
                    while (!sr.EndOfStream)
                        {
                            string sor = sr.ReadLine();
                            string[] elemek = sor.Split(' ');
                            adatlista adat = new adatlista();
                            adat.lista.Add(new adatok());
                            adat.lista[db].telepules=elemek[0];
                            adat.lista[db].ido = elemek[1];
                            adat.lista[db].szeliranyes_erosseg = elemek[2];
                            adat.lista[db].homerseklet = Int32.Parse(elemek[3]);
                            db++;
                        }
                Random rd = new Random();
                int rand_num = rd.Next(1, db);
            }
          }
     }
    /* */
    class felhasznalo
    {
        //adatlista adat = new adatlista();
        foreach (string[] elem in adatlista)
        {
         
        }
    }
       class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
        }
}
obviously I don't want to create all the time new instances but use the created and filled up one already, thank you.
 
Last edited:
Top Bottom