C# FileStream creating new .csv file but not writing to it -
hi i'm trying write data .csv file. code creating new file isn't writing it. here shorter version of code name, age, , sex variables predetermined. in actual application these variables come textboxes (i have made sure data textboxes filling these variables using messagebox).
here code:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.io; namespace consoleapp1 { class program { static void main(string[] args) { string filepath = "c:\\users\\jamie\\desktop\\test.csv"; string name = "jamie"; int age = 69; string sex = "male"; if (!(file.exists(filepath))) { filestream fs = new filestream(filepath, filemode.createnew, fileaccess.write); if (fs.canwrite) { string columntitles = "name,age,sex\n"; fs.write(encoding.ascii.getbytes(columntitles), 0, 0); string input = name + "," + age + "," + sex + "\n"; fs.write(encoding.ascii.getbytes(input), 0, 0); fs.flush(); fs.close(); } } else { filestream fs = new filestream(filepath, filemode.append, fileaccess.write); if (fs.canwrite) { if (new fileinfo(filepath).length == 0) { string columntitles = "name,age,sex\n"; fs.write(encoding.ascii.getbytes(columntitles), 0, 0); } string input = name + "," + age + "," + sex + "\n"; fs.write(encoding.ascii.getbytes(input), 0, 0); fs.flush(); fs.close(); } } } } }
use following code write :
fs.write(encoding.ascii.getbytes(input), 0, asciiencoding.ascii.getbytecount(input));
third argument of filestream write method need know maximum numbers of bytes write. specifying 0 byte maximum byte write in case it's not writing file.
apart error, suggest use using statement filestream implements idisposable interface , take care of flusing stream goes out of scope of using statement.
using(filestream fs = new filestream(filepath, filemode.createnew, fileaccess.write)) { if (fs.canwrite) { string columntitles = "name,age,sex\n"; fs.write(encoding.ascii.getbytes(columntitles), 0, 0); string input = name + "," + age + "," + sex + "\n"; fs.write(encoding.ascii.getbytes(input), 0, asciiencoding.ascii.getbytecount(input)); } }
Comments
Post a Comment