itextSharp重命名重复的文件名

时间:2018-08-08 13:30:20

标签: c# .net wpf itext

我正在使用iTextSharp创建PDF文件,文件名是当天的日期。我希望使用相同的文件名给它们提供编号,例如08-08-2018(1),08-08-2018(2)等。下面是我的代码。请帮助我。

string filename = DateTime.Now.ToString("dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Document document = new Document(PageSize.A4.Rotate(), 25f, 25f, 30f, 160f);
//PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
string pdfFilePath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\InvoicesSummary\";
PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(pdfFilePath + "/" + filename + ".pdf", FileMode.Create));
document.Open();

1 个答案:

答案 0 :(得分:2)

您可以使用File.Exists方法检查同名文件是否已存在。像这样:

string pdfFilePath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\InvoicesSummary\";
string baseFilename = pdfFilePath + "/" + DateTime.Now.ToString("dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string filename = baseFilename;
int n = 1;
while (System.IO.File.Exists(filename + ".pdf"))
    filename = baseFilename + "(" + n++ + ")";

Document document = new Document(PageSize.A4.Rotate(), 25f, 25f, 30f, 160f);
PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(filename + ".pdf", FileMode.Create));
document.Open();