Hello. This is my first post. Hopefully the first of many. I am currently starting my journey in collegiate Computer Science and as such I know some basics about programming - logic and a fledgling understanding of some languages.

Right now I am trying to create a program that uses StreamWriter and StreamReader objects to open two text files. One to read from and one to write to. The point is to build a comma-separated values parser. I'm not doing this for school, I just want to practice.

I'd like to note that I got the program to work. It printed the headers just fine. I had unexpected results with the read/write. It was able to do both, but some of the info was garbled.

The problem I have now is, even though my desk-check looks fine and it compiles fine, it doesn't write ANYTHING. Not even the headers. I have tried starting with an existing file, and starting without and it doesn't matter. All I get is a blank .txt file. My next step is to just start over, verifying that at each step the program is working correctly, however I figured I would try some DaniWeb advice. Be gentle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FirstTry
{
    class Program
    {
        public static void Main(string[] args)
        {
            string newTextFilePath = @"C:\Users\Richard\Documents\Visual Studio 2008\Projects\FirstTry\CSV_File1.txt";
            string valueTextFilePath = @"C:\Users\Richard\Documents\Visual Studio 2008\Projects\FirstTry\CSV_FileValues.txt";
            char[] buffer = new char[1];
            const char DELIMIT = ',';
            char[] field = new char[255];
            byte buffCount = 0;

            string[] HEADERS = new string[5] {"NAME", "ADDRESS", "CITY", "STATE", "ZIPCODE"};

            try
            {
                if (File.Exists(newTextFilePath)) // Checks to see if the output file exists
                {
                    Console.WriteLine("The file exists, deleting now ...");
                    Console.Read();
                    File.Delete(newTextFilePath);
                }

                StreamWriter sw = new StreamWriter(newTextFilePath); // Creates new file from newTextFilePath

                if (File.Exists(newTextFilePath)) // Checks to see if the output file exists
                {
                    Console.WriteLine("The file has been recreated");
                    Console.Read();
                }

                    for (int i = 0; i < HEADERS.Length; i++) // Loop that controls the writing of the headers
                    {
                        sw.Write(HEADERS[i]);
                        if (i < HEADERS.Length -1)
                        {
                            sw.Write(DELIMIT + " ");
                        }
                    }
                    sw.Write("\n");
                

                StreamReader sr = new StreamReader(valueTextFilePath); // Opens existing file for reading

                if (File.Exists(valueTextFilePath))
                {
                    while(sr.Peek() != -1) // Checks next char for EOF
                    {
                        sr.Read(buffer, 0, buffer.Length); // Reads next char into buffer

                        if (buffer[0].Equals(DELIMIT)) // Control break logic checks char for ','
                        {
                            for (int k = 0; k < buffCount; k++)
                            {
                                sw.Write(field[k]); // If control breaks then write field
                            }
                                sw.Write(DELIMIT + " ");
                                buffCount = 0;
                        }
                         else
                        {
                            field[buffCount] = buffer[0]; // If char doesn't equal ',', add char to field
                            buffCount++;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("File read failed: file doesn't exist");
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("The process failed: ", e.ToString());
            }

        }
    }
}

Recommended Answers

All 6 Replies

You need to close your streams to flush the stream buffers before the app closes.

You need to close your streams to flush the stream buffers before the app closes.

So use the explicit .Close() method? I was reading about the Using statement:

Using(StreamWriter sw = new StreamWriter(path)){
   
   statement;

}

Is this better to use in my case, or only when there is a lot more code and more streams to deal with? Thanks for any help.

Yes. It's ok to use using in your case.
But you should still really call Close rather than leave it to the Dispose method to clean up.

So use the explicit .Close() method? I was reading about the Using statement:

Using(StreamWriter sw = new StreamWriter(path)){
   
   statement;

}

Is this better to use in my case, or only when there is a lot more code and more streams to deal with? Thanks for any help.

Since StreamWriter implements IDisposable , you can wrap the StreamWriter in a using block. At the end of block execution Dispose will be called...which will Flush and Close the Stream for you. However, I would like to suggest to keep flushing each of them after each operation to make sure you don't end up with odd data.

Thank you guys for the help. It worked. I tried just using .Flush() on the writer object after it's constructor, however this didn't work. It wasn't until I closed both objects that the program ran smoothly.

Your welcome. If solved, then please mark the thread solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.