c# - Avoid "file in use by another process" IO exception -
the code have included below writes csv file. if csv file writing happens open in excel, system.io.exception
indicates "the file being used process."
how can change code program continuing running , wait until csv no longer open in excel?
private void timer1_tick(object sender, eventargs e) { int actmonth, actyear, actsecond; system.datetime fecha = system.datetime.now; actmonth = fecha.month; actyear = fecha.year; if (actmonth <= 9) { valorfechaact = system.convert.tostring(actyear) + "00" + system.convert.tostring(actmonth); } else { valorfechaact = system.convert.tostring(actyear) + "0" + system.convert.tostring(actmonth); } actsecond = fecha.second; string label; label = label1.text; string @ = "@"; string filename = valorfechaact + ".csv"; string ruta3 = system.io.path.combine(at, label, filename); if (directory.exists(label1.text)) { streamwriter wr = new streamwriter(ruta3, true); wr.writeline("1asd" + actsecond); wr.close(); wr.dispose(); } else { system.console.writeline("no se puede escribir en el archivo"); timer1.stop(); } }
you can write methode try open file filestream , return boolean flag
a possible solution
public static class fileinfoextension { public static bool islocked(this fileinfo file) { filestream stream = null; try { stream = file.open(filemode.open, fileaccess.read, fileshare.none); } catch (ioexception) { return true; } { stream?.close(); } return false; } }
then can use
var fileinfo = new fileinfo(ruta3); if (!fileinfo.islocked()) { // code }
a simple (and bad) solution wait is
while (file.islocked()) { thread.sleep(100); }
general code unclear , difficult read.
you have redudant code , few variable bad named. maybe guidline can https://github.com/dennisdoomen/csharpguidelines
maybe little bit clearer solution is
private void timer1_tick(object sender, eventargs e) { var directory = label1.text; if (!directory.exists(directory)) { console.writeline("no se puede escribir en el archivo"); timer1.stop(); return; } var = datetime.now; _valorfechaact = now.month <= 9 ? $"{now.year}00{now.month}" : $"{now.year}0{now.month}"; var fullname = path.combine("@", directory, $"{_valorfechaact}.csv"); var fileinfo = new fileinfo(fullname); if (fileinfo.islocked()) { console.writeline($"the file {fullname} locked!"); return; } using (var wr = new streamwriter(fullname, true)) { wr.writeline("1asd" + now.second); } }
wiki
Comments
Post a Comment