为什么我的代码无法在项目中找到路径?

时间:2019-04-28 09:01:57

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

我正在使用它合并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;
    }
}

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

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

我不明白为什么它会进入C驱动器,因为文件位于同一项目中。

enter image description here

1 个答案:

答案 0 :(得分:2)

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

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

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

(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"); 
..
相关问题