I'm trying to create a temp file, write to it, print it, then delete it. Here's my 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 the file after it has been printed
File.Delete(filePathReceipt);
}
I get the Exception Message saying:
Can't write to it because it's used by another process.
EDIT #2:
I found that this works:
string filePathReceipt = AppDomain.CurrentDomain.BaseDirectory + @"receipt.txt";
While this generates an 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 the file after it has been printed
File.Delete(filePathReceipt);
}