Search code examples
c#filestreamwriter

writing in a file using C# StreamWriter


I was practicing to write into a file using c#

my code is not working (writing in file is not done)

{
    int T, N; //T = testCase , N = number of dice in any Test
    int index = 0, straight;
    List<string> nDiceFaceValues = new List<string>(); //List for Dice Faces
    string line = null;  //string to read line from file
    string[] lineValues = {};  //array of string to split string line values

    string InputFilePath = @ "E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.in"; //path of input file
    string OuputFilePath = @
    "E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.out"; //path of otput file

    StreamReader InputFile = new StreamReader(InputFilePath);
    StreamWriter Outputfile = new StreamWriter(OuputFilePath);

    T = Int32.Parse(InputFile.ReadLine());  //test cases input
    Console.WriteLine("Test Cases : {0}", T);

    while (index < T) {
        N = Int32.Parse(InputFile.ReadLine());
        for (int i = 0; i < N; i++) {
            line = InputFile.ReadLine();
            lineValues = line.Split(' ');

            foreach(string j in lineValues)
            {
                nDiceFaceValues.Add(j);
            }
        }
        straight = ArrangeDiceINStraight(nDiceFaceValues);
        Console.WriteLine("case:  {0} , {1}", ++index, straight);

        Outputfile.WriteLine("case:  {0} , {1}", index, straight);
        nDiceFaceValues.Clear();
    }
}

what is wrong with this code?

how I fix it?

why its not working??

Note: I want to write in file line by line


Solution

  • What's missing is: closing things down - flushing the buffers, etc:

    using(var outputfile = new StreamWriter(ouputFilePath)) {
        outputfile.WriteLine("case:  {0} , {1}", index, straight);
    }
    

    However, if you're going to do that for every line, File.AppendText may be more convenient.

    In particular, note that new StreamWriter will be overwriting by default, so you'd also need to account for that:

    using(var outputfile = new StreamWriter(ouputFilePathm, true)) {
        outputfile.WriteLine("case:  {0} , {1}", index, straight);
    }
    

    the true here is for append.

    If you have opened a file for concurrent read/write, you could also try just adding outputfile.Flush();, but... it isn't guaranteed to do anything.