Frage

Is there any chance that fileStream object will likely be destroyed before its call to the Close method as below?

FileStream fileStream = new FileStream(xxx);
StreamReader txtReader = new StreamReader(fileStream);

curLog = txtReader.ReadToEnd();

txtReader.Close();
fileStream.Close();
War es hilfreich?

Lösung

Is there any chance that fileStream object will likely be destroyed before its call to the Close method as below?

No.

But you should never write code like that. You should always wrap IDisposable resources in using statements to ensure that they will be disposed even if an exception is thrown and that you won't be leaking handles.

using (FileStream fileStream = new FileStream(xxx))
using (StreamReader txtReader = new StreamReader(fileStream))
{
    curLog = txtReader.ReadToEnd();
}

But for the purpose of this specific example you could simply use the ReadAllText method.

string curLog = File.ReadAllText(xxx);

Andere Tipps

No, there isn't any chance that it is closed before that. And i would recommend using it like this

FileStream fileStream = new FileStream(xxx);
using (StreamReader txtReader = new StreamReader(fileStream))
{
            curLog = txtReader.ReadToEnd();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top