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

问题描述 投票:0回答:1

我用它来合并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驱动器,因为文件在同一个项目中。

enter image description here

c# asp.net c#-4.0 itext
1个回答
2
投票

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

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

可以通过在solution explorer下选择文件来设置文件属性。

(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"); 
..
© www.soinside.com 2019 - 2024. All rights reserved.