c# - Reading file after writing it -
i have strange problem. code follows following.
the exe takes data user
call web service write(and create csv data) file @ perticular network location(say \some-server\some-directory). although web service hosted @ same location folder (i.e can change c:\some-directory). returns after writing file
the exe checks file exists, if file exists further processing else quite error.
the problem having @ step 3. when try read file after has been written, file not found exception(but file there present). not exception when debugging (because putting delay debugging code) or when thread.sleep(3000)
before reading file.
this strange because close streamwriter
before return call exe. according documention, close should force flush of stream. not related size of file. not doing async thread calls writing , reading file. running in same thread serially 1 after another(only writing done web service , reading done exe. still call serial)
i not know, feels there time difference between file gets written on disk , when close()
. baffling because not @ related size. happens file size. have tried file 10, 50, 100,200 lines of data.
another thing suspected since writing file network location, windows optimizing call writing first cache , network location. went ahead , changed code write on drive(i.e use c:\some-directory), rather network location. resulted in same error.
there no error in code(for reading , writing). explained earlier, putting delay, starts working fine. other useful information
- the exe .net framework 3.5
- windows server 2008(64 bit, 4 gb ram)
edit 1 file.appendalltext()
not correct solution, creates new file, if not exits
edit 2 code writing
using (filestream fs = new filestream(outfilename, filemode.create)) { using (streamwriter writer = new streamwriter(fs, encoding.unicode)) { writer.writeline(somestring) } }
code reading
streamreader rdr = new streamreader(file.openread(csvfilepath)); string header = rdr.readline(); rdr.close();
edit 3 used textwriter, same error
using (textwriter writer = file.createtext(outfilename)) { }
edit 3 suggested users, doing check file in while loop number of times before throw exception of file not found.
int = 1; while (i++ < 10) { bool fileexists = file.exists(csvfilepath); if (!fileexists) system.threading.thread.sleep(500); else break; }
so writing stream file, reading file stream? need write file post process it, or can not use source stream directly?
if need file, use loop keeps checking if file exists every second until appears (or silly amount of time has passed) - writer give error if couldn't write file, know turn eventually.
Comments
Post a Comment