سؤال

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();
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top