c# - How can I open a file for writing that safely allows other programs to read? -


i'm opening filestream , writing lines using following 2 code snippets:

public static system.io.filestream openfilestream(string fullfilename) {     return new system.io.filestream(fullfilename, system.io.filemode.openorcreate,         system.io.fileaccess.readwrite, system.io.fileshare.read); }  public static void writeline(system.io.filestream filestream, string str) {     filestream.seek(0, system.io.seekorigin.end);     byte[] bytes = system.text.encoding.utf8.getbytes(str + "\r\n");     filestream.write(bytes, 0, bytes.length);     filestream.flush(); } 

the file being accessed, i.e. fullfilename parameter in openfilestream, csv file. once file has been opened, requirement able see what's been written csv file far.

i've been using microsoft excel that, , when excel opens file, notices file in use , gives me dialog box tells me can read-only access. nonetheless, act of excel trying open file causes exceptions thrown in program that's got open filestream, though access openfilestream grants other programs system.io.fileshare.read.

the exception gets thrown system.io.ioexception message the process cannot access file because process has locked portion of file, , can thrown @ point in writeline function accesses filestream.

how can prevent exceptions ever being thrown program excel trying read file?

what doing everytime write string end of file. prevent 'hogging' file can close file everytime write it.

the default encoding streamwriter utf8

public static void writeline(string filename, string str)  {     using (filestream fs = new filestream(filename,filemode.append, fileaccess.write, fileshare.read))     using (streamwriter sw = new streamwriter(fs))     {         sw.writeline(str);     } } 

Comments