Skip to content

Instantly share code, notes, and snippets.

@rtipton
Created April 20, 2010 00:30
Show Gist options
  • Save rtipton/371850 to your computer and use it in GitHub Desktop.
Save rtipton/371850 to your computer and use it in GitHub Desktop.
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();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment