tirsdag 28. april 2009

Working with text files

// 1) Write to a text file
public void WriteToFile(string file)
{
//create a TextWriter then open the file
TextWriter writer = new StreamWriter(file);
//now write the date to the file
writer.WriteLine(DateTime.Now);
//close the writer
writer.Close();
}

// 2) Read a single line from text file
public void readALine(string file)
{
//create a new TextReader then open the file
TextReader reader = new StreamReader(file);
//read a single line from the file
reader.ReadLine();
}

// 3) Read entire file into a variable then
// return the contenxt
public string ReadWholeFile(string file)
{
//create a string variable to hold the file contents
string fileContents;
//create a new TextReader then open the file
TextReader reader = new StreamReader(file);
//loop through the entire file
while (reader.Peek() != -1)
{
//add each line to the fileContents variable
fileContents += reader.ReadLine().ToString();
}
//close the reader
reader.Close()
//return the results
return fileContents;
}

Ingen kommentarer:

Legg inn en kommentar