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

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -