.net - How to append data to file using SaveFileDialog -
i want write data file, use savefiledialog
object:
public class form3 inherits form public callerform3to1 form1 dim filestream stream = nothing dim filesw streamwriter = nothing private sub form3_load(sender object, e eventargs) handles mybase.load savefiledialog1.filter = "txt files (*.txt)|*.txt|all files (*.*)|*.*" savefiledialog1.filterindex = 2 savefiledialog1.restoredirectory = true flagwritetofile = false if savefiledialog1.showdialog() = dialogresult.ok btn_writedata.enabled = true end if end sub 'some code end class
and after write data opened file:
sub writedatatotext(data long(), appenddata boolean) 'dim new streamwriter(savefiledialog1.openfile(), filemode.append) ' error! filesw = new streamwriter(savefiledialog1.openfile()) if (filesw isnot nothing) filesw.writeline(string.join(" ", data) + environment.newline) filesw.close() end if end sub
what want: need append data file, , overwrite. create appenddata
this: if 1
append if 0
overwrite. know can create streamwriter
file , use filemode
purposes. if use savefiledialog
it's method openfile
returns stream
! , cannot create streamwriter constructor (it takes string not stream).
how append data file using savefiledialog
?
you cannot use openfile append data file selected in savefiledialog.
in msdn documentation savefiledialog.openfile can read
for security purposes, method creates new file selected name , opens read/write permissions. can cause unintentional loss of data if select existing file save to. save data existing file while retaining existing data, use file class open file using file name returned in filename property.
so should write code using filename property streamwriter constructor accepts boolean true append data or false overwrite file.
sub writedatatotext(data long(), appenddata boolean) using filesw = new streamwriter(savefiledialog1.filename, appenddata) filesw.writeline(string.join(" ", data) + environment.newline) end using end sub
remember use using statement around these disposable object sure correct closing , disposing of stream , avoid locking conditions
instead using file class write
dim newline = string.join(" ", data) + environment.newline) if appenddata file.appendalltext(savefiledialog1.filename, newline) else file.writealltext(savefiledialog1.filename, newline) end if
Comments
Post a Comment