Having some trouble to delete a file using FileStreams in C# -
i'm writing program uses text files in c#. use parser class interface between file structure , program. class contains streamreader, streamwriter , filestream. use filestream common stream reader , writer, else these 2 conflict when both of them have file open.
the parser class has class variable called m_path, path file. i've checked extensively, , path correct. openstreams() , and resetstreams() work perfectly, after calling closestreams() in delete() function, program goes catch clause, file.delete(m_path) won't executed. in other situations closestreams() function works perfectly. goes wrong when i'm trying close streamreader (m_writer), give exception (file closed).
/** * function close streams. */ private void closestreams() { if (m_streamopen) { m_fs.close(); m_reader.close(); m_writer.close(); // goes wrong m_streamopen = false; } } /** * deletes file. */ public int delete() { try { closestreams(); // catch after file.delete(m_path); return 0; } catch { return -1; } } i call function this:
parser.delete(); could give me tips?
your file.delete(m_path); never called, because exception here:
private void closestreams() { if (m_streamopen) { m_fs.close(); m_reader.close(); m_writer.close(); // throws exception here m_streamopen = false; } } the exception "cannot access closed file"
the cause explained in documentation of close() in streamreader:
closes system.io.streamreader object , underlying stream, , releases system resources associated reader.
there articles behaviour:
does disposing streamreader close stream?
is there way close streamwriter without closing basestream?
can keep streamreader disposing underlying stream?
avoiding dispose of underlying stream
you should consider re-writing code , use using() statements.
however, experimented bit code, , worked calling close() in other order:
m_writer.close(); m_reader.close(); m_fs.close(); however, assume works coincidence (i used .net 4.0 , not work in .net version). advice not in way.
i tested this:
using (filestream fs = new filestream(m_path, filemode.openorcreate, fileaccess.readwrite, fileshare.none)) using (streamreader reader = new streamreader(fs)) using (streamwriter writer = new streamwriter(fs)) { // work here } file.delete(m_path); but, know may not you, since may want read , write streams available fields in class.
at least, have samples start ...