No need to declare
FileStream fileStream
outside the method using this object. Probably, you never should do it. This way, you're using a local variable instead of the class field. Always prefer local whenever possible. Do in under
using
block -- it will call Dispose automatically at the end of block even if there was an exception.
using (fileStream stream = new FileStream("aaaaa.txt", FileMode.Create) {
stream.Write
}
You called
Dispose
anyway, which is very bad, you could have lost file records because nothing did the flush.
Also, you could better use
StreamWriter
instead:
using (StreamWriter writer = new StreamWriter("aaaaa.txt") {
writer.Write
}
Also, keyword "private" is C# default (for class or structure members -- thanks to Manfred for correction, see his comment below), can be omitted.
[EDIT] This is how to apply the same principle to Easy. First, implement
System.IDisposable
:
public delegate System.Int32
WriteData(
FileStream stream,
byte[] buf, Int32 size, Int32 nmemb, bbject extraData);
class Easy : System.IDisposable {
public Easy(FileStream stream, WriteData onWriteData) {
this.Stream = stream;
this.OnWriteData = onWriteData;
}
public void Perform() {
}
void System.IDisposable.Dispose() {
try {
CleanUp();
} finally {
if (Stream != null)
Stream.Dispose();
}
}
void CleanUp() { }
FileStream Stream;
}
This is how to use it:
partial class MyForm {
void MyButtonClickHandler() {
using (Easy easy =
new Easy(
new FileStream("fname.aaa",
FileMode.Create), OnWriteData)) {
Easy.Perform();
}
}
System.Int32 OnWriteData(
FileStream stream,
byte[] buf, Int32 size, Int32 nmemb, bbject extraData)
{
stream.Write(buf, 0, buf.Length);
return size * nmemb;
}
}
Finally, this is how to use
MyButtonClickHandler
-- better way:
MyButton.Click += (sender, eventArgs) => { MyButtonClickHandler(); };
I don't know your C# version, there is no lambda for v.2.0, but you still better of with anonymous:
MyButton.Click += delegate( object sender, System.EventArgs eventArgs) {
MyButtonClickHandler();
};