Cinnamonbun Cinnamonbun - 23 days ago 6
C# Question

Cannot convert from 'System.IO.FileStream' to 'int' when reading text file into a List

All I want to do is have the program read a .txt file, take whatever is in the file, and input it into a list. But it will tell me I can't convert it (no matter if I set the variable as var, string, int, or whatever) I tried using int.TryParse, Convert.ToInt32(), etc. While Convert.ToInt32 shuts it up, when I run the program it crashes.

static void Main(string[] args)
{
string listPath = @"K:\listData\listData.txt";
int listDataSum = 0;
int listDataMax = 0;
int listDataMin = 0;
string userInput = null;

var numeralListData = System.IO.File.OpenRead(listPath);
var listData = new List<int>(numeralListData);
listDataSum = listData.Sum();
listDataMax = listData.Max();
listDataMin = listData.Min();

Console.WriteLine(
"Please input the data you wish to see, type 'help' for what to type");
userInput = Console.ReadLine();
userInput.ToLower();

if (userInput == "sum")
{
Console.WriteLine("The sum of the list is " + listDataSum);
}


EDIT: If the question is a duplicate, please send the link, I tried the search function and all the other questions were way too complicated for someone with as little experience as me to understand.

Answer

If you are trying to read integers from a file, then get their min, max and sum you will want to read each line into a array of strings, then try and convert each string to an int and add it to a list.

static void Main(string[] args)
{
    string listPath = @"K:\listData\listData.txt";
    int listDataSum = 0;
    int listDataMax = 0;
    int listDataMin = 0;
    string userInput = null;

    var fileReader = new System.IO.StreamReader(listPath);
    List<string> stringsFromFile = new List<string>();
    string lineOfText;
    while ((lineOfText = fileReader.ReadLine()) != null)
    {
        stringsFromFile.Add(lineOfText);
    }
    List<int> intsFromFile = new List<int>();
    foreach(string s in stringsFromFile)
    {
        int temp = 0;
        if(Int32.TryParse(s, out temp))
        {
            intsFromFile.Add(temp);
        }            
    }

    listDataSum = intsFromFile.Sum();
    listDataMax = intsFromFile.Max();
    listDataMin = intsFromFile.Min();

    Console.WriteLine("Please input the data you wish to see, type 'help' for what to type");
    userInput = Console.ReadLine();
    userInput.ToLower();

    if (userInput == "sum")
    {
        Console.WriteLine("The sum of the list is " + listDataSum);
    }
}
Comments