1

I am working on Console Application and I am trying to save list to txt file and read that data later.

In program user inputs name of category and I am not sure how to save that with list in txt file.

Struct Category that holds name.

struct Category
{
    public string name;
}

This is my code so far.

Category k;

Console.WriteLine("Enter name of category: ");
k.name = Console.ReadLine();

List<String> category = new List<string>();


TextWriter tw = new StreamWriter("../../dat.txt");

foreach (string k in category)
{

    string[] en = s.Split(','); 
    category.Add(k.name); // Here I am not sure how to save name
}
tw.Close();

StreamReader sr = new StreamReader("../../dat.txt");

string data = sr.ReadLine();

while (data != null)
{

    Console.WriteLine(data);
    data = sr.ReadLine();
}
sr.Close();

It doesn't give me any error but it's not writing name to txt file.

SOLUTIN

string filePath = @"../../datoteka.txt";
List<String> kategorije = File.ReadAllLines(filePath).ToList();

foreach (string s in kategorije)
{

Console.WriteLine(s);

}
kategorije.Add(k.naziv);
File.WriteAllLines(filePath,kategorije);
7
  • 1
    You don't actually write anything using the TextWriter i.e. I would expect to see tw.WriteLine(k.Name) or similar. Commented Jan 28, 2018 at 18:24
  • Possible duplicate of Saving lists to txt file Commented Jan 28, 2018 at 18:25
  • How to read : stackoverflow.com/q/6904401/1924666 Commented Jan 28, 2018 at 18:26
  • 1
    After category.Add(k.name) add a line tw.WriteLine(k.name) ... Commented Jan 28, 2018 at 18:27
  • 1
    Quite a few problems: you never use tw to actually write anything; you try to foreach through a new, empty list; you define k as a Category struct, then again as the foreach variable; whatever s is in s.Split isn't defined in the code you've shown; the List contains string values, not your Category struct... Commented Jan 28, 2018 at 18:35

2 Answers 2

3

You can use the static methods of the System.IO.File class. Their advantage is that they open and close files automatically, thus reducing the task of writing and reading files to a single statement

File.WriteAllLines(yourFilePath, category);

You can read the lines back into a list with

 category = new List(ReadLines(yourFilePath));

ReadLines returns an IEnumerable<string> that is accepted as data source in the constructor of the list.

or into an array with

string[] array = ReadAllLines(yourFilePath);

Your solution does not write anything to the output stream. You are initializing a TextWriter but not using it. You would use it like

tw.WriteLine(someString);

Your code has some problems: You are declaring a category variable k, but you never assign it a category. Your list is not of type category.

A better solution would work like this

var categories = new List<Category>(); // Create a categories list.
while (true) { // Loop as long as the user enters some category name.
    Console.WriteLine("Enter name of category: ");
    string s = Console.ReadLine(); // Read user entry.
    if (String.IsNullOrWhiteSpace(s)) {
        // No more entries - exit loop
        break;
    }

    // Create a new category and assign it the entered name.
    var category = new Category { name = s };

    //TODO: Prompt the user for more properties of the category and assign them to the
    // category.

    // Add the category to the list.
    categories.Add(category);
}
File.WriteAllLines(yourFilePath, categories.Select(c => c.name));

The Category type should be class. See: When should I use a struct instead of a class?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I managed to fix my code based on it. If you check my question I have put it as solution. :) @Olivier Jacot-Descombes
0

You are not using WtiteLine to write content. Add below code in your solution after

category.Add(k.name);
tw.WriteLine(someString);

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

Find below sample code for read and write.

class WriteTextFile
{
    static void Main()
    {
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";

        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {                   
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }    
        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.