c# - 为什么我的代码在项目中找不到路径?
问题描述
我正在使用它来合并 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
驱动,因为文件在同一个项目中。
解决方案
(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");
..
推荐阅读
- java - 线程转储显示线程未释放锁。
- semantic-mediawiki - 我可以在语义媒体维基中使用属性值作为查询吗?
- python - Python Pandas 到 PySpark:如何在 PySpark 中标记化、删除权宜之计和做三元组
- database - 如何在数据库中保存应用程序密码?
- sql-server - 在 NOT NULL 处重新启动的 NULL 累积计数
- python - 使用 rabbitmq 集成 Nodejs 和 Python
- c++ - 在编译时验证对象是否创建为 shared_ptr
- c# - 我想避免用户使用 mvc 5 同时登录多个地方
- traefik - Kubernetes 上的 Traefik UI 中缺少“最近的 HTTP 错误”
- python - 从 keras 生成器获取真实标签