FileStream 说它找不到路径的一部分

FileStream says it cant find a part of the path

所以我有这个控制台应用程序可以在文件夹中查找文件,这个文件夹只有 .tiff 图像,应用程序的重点是将它们全部转换为 pdf 文件,最后合并它们,所以我有这个 foreach 循环

        foreach (var path in Directory.GetFiles(@"C:/Users/tferreira/Desktop/TIF_MarcadAgua"))
        {
            Console.WriteLine(path); // full path
            Console.WriteLine(System.IO.Path.GetFileName(path)); // file name

            Escrever("A fazer pdf");

            imagens.Add(path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
            FazerPdf(path);
            if (File.Exists(path.ToUpper().Replace("A.TIF", "B.TIF")))
            {
                imagens.Add(path.ToUpper().Replace("A.TIF", "B.PDF"));

                FazerPdf(path.ToUpper().Replace("A.TIF", "B.TIF"));
            }
            Escrever("O pdf foi gerado com sucesso. Caminho : " + path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));

            Escrever("Vai fazer o merge de todos os pdfs gerados.");

            PdfMerge pm = new PdfMerge();
            foreach (string imagem in imagens)
            {
                pm.AddDocument(imagem);
                npages++;
            }
        }

所做的是 运行 通过文件夹获取所有文件并将路径存储在该 var 路径变量中。

但是当真正到了制作 pdf 的时候,它给出了我在上面提到的那个错误。

发生错误的那一行是 fazerPDF 函数,那是制作 pdf 的地方,因为它是一个文件路径错误,我将只显示错误行,因为它使事情很容易看到。

    using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
    {
        // some code 
    }

据我所知,图像确实存在,文件夹确实存在。 感谢您的帮助,如果我自己发现它是什么病 post 一个答案。

编辑:

fazerPDF 函数

static public void FazerPdf(string Path)
    {
        string newPath = System.IO.Path.ChangeExtension(Path, ".pdf");
        if (!File.Exists(Path.Replace("TIF", "PDF")))
          
            using (FileStream stream = new FileStream(newPath.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
            {

问题似乎出在这一行:

using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))

这会将 Path 中的所有 "TIF" 实例替换为 "PDF",无论它们出现在何处。例如:

c:\TIFs\IlikeTIFfiles\MyTIF.TIF

会变成:

c:\PDFs\IlikePDFfiles\MyPDF.PDF

如果你只是想替换路径中的文件扩展名部分,可以使用Path.ChangeExtension将旧的扩展名剪掉并添加新的:

string newPath = System.IO.Path.ChangeExtension(path, ".pdf");
using (FileStream stream = new FileStream(newPath, FileMode.Create, FileAccess.Write))

以上面的例子为例,@"c:\TIFs\IlikeTIFfiles\MyTIF.TIF" 将变成 @"c:\TIFs\IlikeTIFfiles\MyTIF.pdf"

See it in action.