F D

F D

  • NA
  • 45
  • 81.1k

C Sharp Code to output text file

Aug 28 2013 10:00 AM
Hello guys, 

I have a console app in C sharp in visual studio 2008 to reformat a text file. How do I display the information into the console window and output that information to a text file when I run the program? Below is the code I have thus far.

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

namespace Directory_Listing_Reformat
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        void Main()
        {
            var lines = ReadFile();

            lines.ToList().ForEach(Console.WriteLine);
        }

        IEnumerable<Line> ReadFile()
        {
            using (var reader = new StreamReader(File.OpenRead(@"C:\List.txt")))
            {
                const string directoryPrefix = " Directory of ";
                Regex splittingRegex = new Regex(@"\s+", RegexOptions.Compiled);
                string directory = null;
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    line = line.TrimEnd();
                    if (line.StartsWith(directoryPrefix))
                    {
                        directory = line.Substring(directoryPrefix.Length);
                        continue;
                    }

                    
                    var lineParts = splittingRegex.Split(line, 6);
                    yield return new Line { Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
                }
            }
        }

        // Define other methods and classes here
        class Line
        {
            public string Date { get; set; }
            public string Time { get; set; }
            public string Period { get; set; }
            public string Bytes { get; set; }
            public string User { get; set; }
            public string Filename { get; set; }
        }
    }




Answers (1)