c#.net覆盖提示不起作用

时间:2016-02-28 03:37:19

标签: c# savefiledialog

我有一个用户数据报告需要保存为pdf,但当我将覆盖提示设置为true时,如果没有显示存在的文件名,则覆盖消息。这是我的代码。

SaveFileDialog svg = new SaveFileDialog();
svg.FileName = "Data Report - All Books";//set default file name
svg.Filter = "Pdf Files|*.pdf";

if (svg.ShowDialog() == DialogResult.OK)
{
    svg.OverwritePrompt = true;//tell user to overwrite existing file name
    using (FileStream stream = new FileStream(svg.FileName + ".pdf", FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A1, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, stream);

        pdfDoc.Open();
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        stream.Close();
    }
    MetroMessageBox.Show(this, "Successfully save PDF report.", "SUCESS!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

1 个答案:

答案 0 :(得分:1)

您必须在显示对话框之前设置覆盖提示。 MSDN确实提到默认情况下OverWritePrompt设置为true。

SaveFileDialog svg = new SaveFileDialog();
svg.FileName = "Data Report - All Books";//set default file name
svg.Filter = "Pdf Files|*.pdf";

//This needs to be before dialog is shown.
svg.OverwritePrompt = true;//tell user to overwrite
if (svg.ShowDialog() == DialogResult.OK)
{
    using (FileStream stream = new FileStream(svg.FileName + ".pdf", FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A1, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, stream);

        pdfDoc.Open();
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        stream.Close();
    }
    MetroMessageBox.Show(this, "Successfully save PDF report.", "SUCESS!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}