C#创建临时文件,写入,打印,然后删除它

时间:2017-03-28 10:58:06

标签: c#

我试图创建临时文件,写入,打印,然后删除它。这是我的代码:

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);
}

我收到异常消息说:

  

不能写信给它,因为它是由另一个进程使用的。

编辑#2:编辑#2: 我发现这有效: string filePathReceipt = AppDomain.CurrentDomain.BaseDirectory + @"receipt.txt";

虽然这会产生异常:string filePathReceipt = Path.GetTempFileName();

完整的当前代码:

        //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);
        }

2 个答案:

答案 0 :(得分:5)

您混合了两个概念:FileStreamFile.WriteAllText 您打开文件流,然后使用File.WriteAllText尝试打开文件而无法执行此操作。

替换:

using (FileStream fs = new FileStream(filePathReceipt, FileMode.Open)) {
  File.WriteAllText(filePathReceipt, dataToBeWritten.ToString());
}

使用:

File.WriteAllText(filePathReceipt, dataToBeWritten.ToString());

// pay attention: it is 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());
}

答案 1 :(得分:4)

除了Yeldar's answer ...

您需要等待打印过程完成。启动该过程后,您无法在毫秒内删除该文件。

等待该过程的直接方式是:

try {
    using (Process p = Process.Start(psi))
        p.WaitForExit();
}
catch (Exception ex) {
    MessageBox.Show(ex.Message);
}

另一种方法是使用Process'事件:

using(Process p = new Process())
{
    p.StartInfo = psi;
    p.EnableRaisingEvents = true;
    p.HasExited += OnProcessExited;
}

并在OnProcessExited事件处理程序中处理该文件。