C# Create temp file, write to it, print it, then delete it -


i'm trying create temp file, write it, print it, delete it. here's code:

string filepathreceipt = path.gettempfilename();  try {     using (filestream fs = new filestream(filepathreceipt, filemode.open)) {         file.writealltext(filepathreceipt, datatobewritten.tostring());     } } catch (exception ex) {     messagebox.show(ex.message); }  //printing receipt: start processstartinfo psi = new processstartinfo(filepathreceipt); psi.verb = "print";  try {     process.start(psi); } catch (exception ex) {     messagebox.show(ex.message); } //printing receipt: end  if (file.exists(filepathreceipt)) {     //delete file after has been printed     file.delete(filepathreceipt); } 

i exception message saying:

can't write because it's used process.

edit #2: found works: string filepathreceipt = appdomain.currentdomain.basedirectory + @"receipt.txt";

while generates exception: string filepathreceipt = path.gettempfilename();

full, current code:

        //string filepathreceipt = appdomain.currentdomain.basedirectory + @"receipt.txt";         string filepathreceipt = path.gettempfilename();          file.writealltext(filepathreceipt, datatobewritten.tostring());          processstartinfo psi = new processstartinfo(filepathreceipt);         psi.verb = "print";          try {             using (process p = process.start(psi))                 p.waitforexit();         }         catch (exception ex) {             messagebox.show(ex.message);         }           if (file.exists(filepathreceipt)) {             //delete file after has been printed             file.delete(filepathreceipt);         } 

you mixing 2 concepts: filestream , file.writealltext.
open file stream , use file.writealltext tries open file , fails that.

replace:

using (filestream fs = new filestream(filepathreceipt, filemode.open)) {   file.writealltext(filepathreceipt, datatobewritten.tostring()); } 

with either:

file.writealltext(filepathreceipt, datatobewritten.tostring()); 

or

// pay attention: filemode.create, not filemode.open using (filestream fs = new filestream(filepathreceipt, filemode.create))  using (streamwriter sw = new streamwriter(fs, encoding.utf8)) {   sw.write(datatobewritten.tostring()); } 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -