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!");
        }
    }
}
 
new StreamReader(...)
 
 
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?
 
You have to change the code to use constructor like I've shown you.
 
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");
 
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.
 
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.
 
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");
        }

    }
}
 
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.
 
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
 
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!");
            }
        }
}
 
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
 
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++;
                        }
 

Latest posts

Back
Top Bottom