Read and Write to files

This tutorial is about how to read and write from/to a file (textual file).

First of all define the files that are for the input and output filenames.

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

string fileName = "country.txt";
string outFileName = "sqlcountry.txt";
 
//make sure that the file is present
if (File.Exists(fileName))
{
 
//Setup the output file object, using a StreamWriter to write to files.
       using (StreamWriter SWriter = new StreamWriter(outFileName))
       {
 
//Setup the input file object, 
       using (StreamReader SReader = new StreamReader(fileName))
       {
 
//The line is the input line from the input file.
       String line;
 
//While assigning the line from the input file is valid
       while ((line = SReader.ReadLine()) != null){
 
//Write to the output file some different text.
       SWriter.WriteLine("insert into country(place) values(\"" + line + "\");");
}

I have attached all of the required files to be able to test this tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *