c# - Must manually close StreamWriter in Usings? -
at 2nd iteration, "file being used" error occurs @ "using (streamwriter" line. though streamwriter supposed auto-close after going out of usings.
edit 1: real code
note: mails list<mailmessage>
(instantiated from/to addresses)
foreach (var x in mails) { x.subject = "updated google exchange rates (" + datetime.now.tostring(new cultureinfo("en-us")) + ")"; stringbuilder emailbody = new stringbuilder(); emailbody.appendline("abc"); //<-- simplified x.body = emailbody.tostring(); _txtname = x.subject.replace(...); //replaces invalid file-name chars //note _txtname unique due x.subject's dependency on datetime using (streamwriter sw = new streamwriter("./exchange rate history/" + _txtname)) { sw.writeline(emailbody); sw.close(); } attachment attachment = new attachment("./exchange rate history/" + _txtname); attachment.name = _txtname; x.attachments.add(attachment); smtpclient smtpclient = new smtpclient("...") { credentials = new system.net.networkcredential("", ""), port = 25 }; smtpclient.send(x); smtpclient.dispose(); }
i had add "sw.close();" @ before end of "usings" loop work. why?
edit 2: oh no! sw.close() stopped working! "file being used" again.
found problem, , not streamwriter not closing after usings
.
chris sinclair right datetime
not guaranteeing unique file name. if for-loop short (therefore, fast), can end duplicate names, happened in case.
for 5 emails, _txtname
generated 5 identical file names, meaning ended 1 file in end since streamwriter overwrites default.
also, forgot use x.attachments.dispose();
@ end of each loop. when re-iterated, x.attachments.add()
still trying attach same file (upload time) while streamwriter
begins write same file cause _txtname
generated duplicate names due datetime
being slower for-loop.
tl;dr: for-loop fast furious.
Comments
Post a Comment