0

I wish to take selected data from a collection of csv files, i have written code but confused on its behaviour, it reads them all, what am i doing wrong please.

string[] array1 = Directory.GetFiles(WorkingDirectory, "00 DEV1 2????????????????????.csv"); //excludes "repaired" files from array, and "Averaged" logs, if found, note: does not exclude duplicate files if they exist (yet)

        Console.WriteLine(" Number of Files found with the filter applied = {0,6}", (array1.Length));
        int i = 1;

        foreach (string name in array1)
        {
            // sampling engine loop here, take first line only, first column DateTimeStamp and second is Voltage


            Console.Write("\r      Number of File currently being processed = {0,6}", i);
            i++;

            var reader = new StreamReader(File.OpenRead(name)); // Static for testing only, to be replaced by file filter code
            reader.ReadLine();

            reader.ReadLine(); // skip headers, read and do nothing
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');

                using (StreamWriter outfile = new StreamWriter(@"C:\\SampledFileResults.txt",true))
                {                       
                        string content = "";
                        {
                            content = content + values[0] + ",";
                            content = content + values[9] + ",";
                        }
                        outfile.WriteLine(content);
                        Console.WriteLine(content);
                        }
            }

        } Console.WriteLine("SAMPLING COMPLETED");
                Console.ReadLine();
                Console.WriteLine("Test ended on {0}", (DateTime.Now));
                Console.ReadLine();
            }
        }
StevieB
  • 19
  • 5

1 Answers1

0

You are using a while loop to read through all lines of the file. If you only want a single line, you can remove this loop.

Just delete the line:

while (!reader.EndOfStream)
{

And the accompanying close bracket

}
grovesNL
  • 6,016
  • 2
  • 20
  • 32
  • Thanks, some of my files have null values, how/where do i test for that, on MSDN, they suggest StringisNull Empty method, but surely i need to pull into array first? any assistance greatly welcomed,,, – StevieB Dec 04 '14 at 21:18
  • @StevieB: You can use something like `if(reader.EndOfSTream) continue;` to proceed with the next file in your `foreach` loop, the end of the stream has been reached. – grovesNL Dec 04 '14 at 21:56
  • i have empty files in my dataset, so when i load my array with an empty file, it throws me out, how do i check for an empty file before loading/splitting? Try/Catch etc? – StevieB Dec 04 '14 at 22:02
  • @StevieB: Take a look at this question http://stackoverflow.com/questions/3007711/is-file-empty-check – grovesNL Dec 04 '14 at 22:05