简体   繁体   中英

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM