reading and writing a file

J

John Salerno

I wrote this code just to experiment with writing to and reading from a
file. It seems to work fine when writing, but when reading the file, it
only prints the filepath to the screen, not the file contents.

System.IO.StreamWriter file = new
System.IO.StreamWriter(@"C:\positions.txt");
System.IO.StringReader myFile = new
System.IO.StringReader(@"C:\positions.txt");

for (int i = 0; i < 3; i++)
{
string positions = Console.ReadLine();
file.WriteLine(positions);
}

Console.WriteLine("Will now read from file...");
Console.ReadLine();

for (int i = 0; i < 3; i++)
{
string getPos = myFile.ReadLine();
Console.WriteLine(getPos);
}

file.Close();
Console.ReadLine();


P.S. I followed the examples in C# Express. In other books I've read,
reading/writing of files usually involves a FileStream object too. Is
that not necessary?
 
P

Peter Gummer

John said:
System.IO.StringReader myFile = new
System.IO.StringReader(@"C:\positions.txt");

You're using a string reader. You need a stream reader. Also, you
haven't closed the file after writing to it.

-- Peter Gummer
 
J

John Salerno

Peter said:
John Salerno wrote:




You're using a string reader. You need a stream reader. Also, you
haven't closed the file after writing to it.

-- Peter Gummer

Doh! I typed it in wrong! Thanks!

(embarrassed) :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top