首页 > 解决方案 > 为什么我的代码在项目中找不到路径?

问题描述

我正在使用它来合并 2 个 pad 文件:

public static void MergePages(string outputPdfPath, string[] lstFiles)
{
    lstFiles = new string[2] { @"Downloads\Certificates\119.FDV-3686.pdf", 
                               @"Downloads\Certificates\119.FDV-3686.pdf" };
    outputPdfPath = @"Downloads\Certificates\";

    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage;
    sourceDocument = new Document(); 
    pdfCopyProvider = new PdfCopy(sourceDocument,
    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
    sourceDocument.Open();
    try
    {
        for (int f = 0; f < lstFiles.Length - 1; f++)
        {
            int pages = 1;
            reader = new PdfReader(lstFiles[f]);
            //Add pages of current file
            for (int i = 1; i <= pages; i++)
            {
                importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                pdfCopyProvider.AddPage(importedPage);
            }
            reader.Close();
        }
        sourceDocument.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

这两个文件存在于我的项目目录中,但它会引发错误:

找不到路径“C:\Program Files (x86)\IIS Express\~\Downloads\Certificates\119.FDV-3686.pdf”的一部分。

我不明白为什么它会C驱动,因为文件在同一个项目中。

在此处输入图像描述

标签: c#asp.netc#-4.0itext

解决方案


(1) 一个问题可能是您的设计时 pdf 文件在编译期间未复制到应用程序输出目录。因此它们在运行时不可用。

如果要将文件从解决方案文件夹复制到应用程序输出目录,可以将文件属性“复制到输出目录”设置为“始终复制”或“如果较新则复制”。更多关于主题的讨论见这里

可以通过在解决方案资源管理器下选择文件来设置文件属性。

(2) 另一个问题是你没有设置文件路径的根目录。我建议您使用以下样式表示文件路径:

var rootLocation = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase.ToString()).LocalPath);
var filePath1  = Path.Combine(rootLocation,@"Downloads\Certificates\filename1.pdf"); 
var filePath2  = Path.Combine(rootLocation,@"Downloads\Certificates\filename2.pdf"); 
..

推荐阅读