rtipton
4/20/2010 - 12:30 AM

C# -- Write to a text file

C# -- Write to a text file

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

namespace WriteTextFile
{
    class WriteText
    {
        static void Main(string[] args)
        {
            //- Location of the Text file
            string fileName = @"c:\temp\txt_test.TXT";
            string targetFile = @"c:\temp\txt_test2.TXT";

            //- Set the line counter
            int lineNumber = 0;
            
            //- Open the target text file
            StreamWriter sw = new StreamWriter(targetFile);

            //- Open the source text file and read thru it
            using (StreamReader sr = new StreamReader(fileName))
            {
                //- Initialize name variables
                string aName = "";
                string sName = "";
                string alName = "";
                string line;    //- Holds the entire line

                //- Cycle thru the text file 1 line at a time pulling
                //- substrings into the variables initialized above
                while ((line = sr.ReadLine()) != null)
                {
                    lineNumber++;

                    //- Pulling substrings.  If there is a problem
                    //- with the start index and/or the length values
                    //- an exception is thrown
                    try
                    {
                        aName = line.Substring(0, 21).Trim();
                        sName = line.Substring(22, 25).Trim();
                        alName = line.Substring(47, 17).Trim();
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                    }

                    //- Write the data to a new text file as delimited
                    sw.WriteLine(aName + "~" + sName + "~" + alName);
                }
                //- Close both the StreamReader and StreamWriter
                sr.Close();
                sw.Close();
            }
        }
    }
}