3D-kreativ
3D-kreativ

Reputation: 9297

Error when creating StreamWriter object

I can't solve this error! I get a red underline in VisualStudio 2010 below outfile in the second row. I have written the code exactly as it is in my book.

FileStream outFile = new FileStream("movies.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);

The error message: A field initializer cannot reference the non-static field, method, or property 'MyMovies.FileManager.outFile'

I also have a question about saving a textfile if there is possible to save or replace a string of text at selected row in a file?

EDIT: The code I use to save

 StreamWriter writer = File.CreateText("MinaFilmer/filmer.txt");
 writer.WriteLine("Test");

Upvotes: 0

Views: 2113

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500575

I suspect that in the book, these are local variables, declared inside a method - whereas you're declaring them directly in a class as instance variables.

Do you really want these to be instance variables? Both of them? Where possible, I'd attempt to do this only within a method, so you can keep all the clean-up local to the method.

You could write this:

StreamWriter writer = new StreamWriter(new FileStream("movies.txt", 
                                          FileMode.Create, FileAccess.Write));

although you'd be better with:

StreamWriter writer = File.CreateText("movies.txt");

Then:

I also have a question about saving a textfile if there is possible to save or replace a string of text at selected row in a file?

We'd need more detail to answer that, and it really is a separate question, which should be asked separately.

Upvotes: 1

Related Questions