i need to write data to a file in c# but somehow it shows success but the file is empty -


this question has answer here:

hello code trying : if file existes , append file else create new 1 . need write data line line

                    fileexists = file.exists(newfilename);                     if (fileexists = false)                     {                         using (fs =new filestream(newfilename, filemode.create))                         {                             sw = new streamwriter(fs);                             messagebox.show(record);                             sw.writeline(record);                             fs.close();                         }                     }                     else                     {                         using (fd = new filestream(newfilename, filemode.append))                         {                             sw = new streamwriter(fd);                             messagebox.show(record);                             sw.writeline(record,true);                         }                     }                  } 

this because code never enters fileexists = false branch: assignment, not comparison.

you can add = make comparison (i.e. make fileexists == false) idiomatic way of checking opposite of condition unary operator !.

change condition follows make work:

if (!fileexists)     ... 

in addition, forgot close or flush streamwriter.

you can unify both branches using ternary operator, this:

using (fs =new filestream(newfilename, fileexists ? filemode.append : filemode.create)) {     sw = new streamwriter(fs);     messagebox.show(record);     sw.writeline(record);     sw.close(); // <<== add line     fs.close(); } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -