Samuel Burns
Samuel Burns

Reputation: 7

Why isn't my StreamWriter saving to a textfile?

I have no issues reading the fruits.txt file with streamreader but writing to newFruits.txt seems to not work.

I run the code, with no errors, and then check the newFruits.txt file and see it still blank. I have my properties window of the newFruits.txt screenshot below if that helps. I checked other questions and they didn't seem similiar or understandable. Any suggestions?

using System;
using System.IO;
using System.Globalization;
using System.Threading;

class FruityLoops
{
    static void Main()
    {
        Console.WriteLine("Loading and sorting fruits...");
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;


        StreamReader fruitreader = new StreamReader("fruits.txt");
        string fruitList = fruitreader.ReadLine();
        char x = ',';
        string[] fruitArray1 = fruitList.Split(x);
        Array.Sort(fruitArray1);
        fruitreader.Close();

        StreamWriter fruitwriter = new StreamWriter("newFruits.txt");
        fruitwriter.WriteLine(fruitArray1);
        fruitwriter.Close();

    }
}

Here is a picture of my properties menu for the text file I am trying to write too. See any problems? Not sure if this is a settings problem or code issue.

Here is a picture of my fruits.txt file too.

Upvotes: 0

Views: 707

Answers (3)

Sean83
Sean83

Reputation: 493

  1. You did not mention the element of the array.

you should give an index of the element you want to retrieve.

fruitwriter.WriteLine(fruitArray1[0]);

instead of

fruitwriter.WriteLine(fruitArray1);
  1. Even though it writes, the program would ONLY Read and Write One line.

    Use loop to read and write line and close the StreamReader and StreamWriter after reading all the lines.

Upvotes: 0

tmaj
tmaj

Reputation: 35135

The code works, but it saves the newFruits.txt file into bin\Debug or bin\Release directory where the program runs, not into newFruits.txt file that is part of your project.

Major comments:

  1. The code will write System.String[] into the output file
  2. StreamWriters should be wrapped in using statements.

Upvotes: 1

Joseph Wu
Joseph Wu

Reputation: 5028

you should pass one string line at a time when using 'WriteLine' method:

        for (int i = 0; i < fruitArray1.Length -1 ; i++)
        {
            fruitwriter.WriteLine(fruitArray1[i])
        }

Upvotes: 3

Related Questions