【问题标题】:itextSharp rename duplicate file nameitextSharp 重命名重复文件名
【发布时间】:2018-08-08 13:30:19
【问题描述】:

我正在使用 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();

【问题讨论】:

  • 所以您的问题是检查文件夹中有多少文件与特定模式匹配以命名您要创建模式的文件(count_of_files_plus_one)。我想知道这与 wpf 或 itext 有何关系
  • tusi saray ni maa di budi ay kam az kam flag tay ni karyeo jadon answer dean da chut ich zor nahi gando

标签: c# .net wpf itext


【解决方案1】:

您可以使用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();

【讨论】:

  • 你需要做一个baseFilename变量,把第五行改成filename = baseFilename + ...;否则你会得到“08-08-2018(1)(2)(3).pdf”。
  • @AdamV 你是对的。它导致了您提到的问题。
  • @AdamV:谢谢。固定。
  • 您需要添加一个.ToString() 才能将"(" 与整数变量连接起来。
  • @bradbury9:不,我不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 2015-12-11
  • 1970-01-01
  • 2016-01-25
  • 2018-04-26
  • 2014-09-09
  • 1970-01-01
相关资源
最近更新 更多