How do we use FileMode.Append on C#? -


i've been trying come way code open file or create 1 (if given file name non-existent). afterwards, run program end creating array , want contents of array converted string , appended file creating , opening. i've got right except 'append' part. in end "object reference not set instance of object." can please enlighten me on one? appreciated.

        try         {             filestream fs = new filestream("inventory.ini", filemode.openorcreate, fileaccess.read);             streamreader reader = new streamreader(fs);              while (!reader.endofstream)             {                 string line = reader.readline();                 string[] data = line.split('|');                 int code = int.parse(data[0]);                 string name = data[1];                 double price = double.parse(data[2]);                  item item = new item(code, name, price);                 app.array[inventorycount++] = item;                 }              reader.close();             fs.close();         }          catch (exception e)         {             console.writeline(e.message);         }          app.run();          try         {             filestream fs = new filestream("inventory.ini", filemode.append, fileaccess.write);             streamwriter writer = new streamwriter(fs);              foreach (item item in app.array)             {                 writer.writeline(item.code + "|" + item.name + "|" + item.price);             }              writer.close();             fs.close();         }          catch (exception e)         {             console.writeline(e.message);         }         console.readline();     } 

you can use constructor of streamwriter, allows appending, , write this:

streamwriter writer = new streamwriter("inventory.ini", true); 

i never used filestream in apps, streamwriter has been quite reliable. can switch using statement, don't need close().

also suggest switching lists, have exact amount of items need inside app.array (which btw needs better name). this:

app.array[inventorycount++] = item; 

will change this:

app.list.add(item); 

aside memory management headache relief, no longer need inventorycount variable, since can value list.count;

the general approach here minimize amount of code need write, same amount of functionality. have no place error lurk.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -