You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

删除不同文件夹文件时遇“被其他进程占用”报错,求代码修正方案

Hey there, let's tackle your two issues one by one—first the frustrating "file in use" error when deleting files, then fixing that incomplete PDF watermark code.


1. Fixing "File in Use" Error When Deleting Files from Multiple Folders

That error almost always boils down to one of two things: a file stream you opened wasn't properly released, or an external process (like antivirus, file explorer preview, or another app) has locked the file temporarily. Here's a robust solution:

Key Fixes & Code Example

using System.IO;
using System.Threading;

public void DeleteFilesFromFolders(params string[] folderPaths)
{
    foreach (var folderPath in folderPaths)
    {
        if (!Directory.Exists(folderPath))
        {
            Console.WriteLine($"Skipping: Folder {folderPath} doesn't exist.");
            continue;
        }

        foreach (var filePath in Directory.GetFiles(folderPath))
        {
            bool isDeleted = false;
            int retryAttempts = 3; // Give temporary locks time to release

            while (!isDeleted && retryAttempts > 0)
            {
                try
                {
                    // Critical: Ensure no internal streams are holding the file
                    // If you previously read/wrote this file, use `using` statements to auto-dispose streams
                    File.Delete(filePath);
                    isDeleted = true;
                    Console.WriteLine($"Successfully deleted: {filePath}");
                }
                catch (IOException ex)
                {
                    retryAttempts--;
                    Console.WriteLine($"Failed to delete {filePath}: {ex.Message}. Retrying in 1s... ({retryAttempts} left)");
                    Thread.Sleep(1000); // Wait for external processes to release the lock
                }
            }

            if (!isDeleted)
            {
                Console.WriteLine($"Permanent failure: Could not delete {filePath} after 3 attempts.");
            }
        }
    }
}

How to Use It

Call it with your two folder paths like this:

DeleteFilesFromFolders(@"C:\FirstFolder", @"D:\SecondFolder");

2. Fixing the PDF Watermark Insertion Code

Your snippet cuts off, so I'll assume you're using iText7 (the modern, supported version of iText). First, install the NuGet package: Install-Package iTextSharp.LGPLv2.Core (or the official iText7 package if you have a license).

Here's the complete, fixed code with proper resource management (which also helps avoid "file in use" errors later):

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
using System.IO;

public bool InsertWaterMark(string path)
{
    bool valid = true;
    try
    {
        // Use Path.Combine to avoid messy string concatenation and path errors
        string originalFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
        string destinationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content", path);

        // Make sure the destination folder exists before saving
        Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath));

        // Using statements auto-dispose PDF readers/writers to release file locks
        using (PdfReader reader = new PdfReader(originalFilePath))
        {
            using (PdfWriter writer = new PdfWriter(destinationFilePath))
            {
                using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
                {
                    Document document = new Document(pdfDoc);
                    int totalPages = pdfDoc.GetNumberOfPages();

                    // Customize your watermark here (text, size, opacity, alignment)
                    Paragraph watermarkText = new Paragraph("CONFIDENTIAL")
                        .SetFontSize(45)
                        .SetOpacity(0.25f)
                        .SetTextAlignment(TextAlignment.CENTER);

                    // Add watermark to every page
                    for (int pageNum = 1; pageNum <= totalPages; pageNum++)
                    {
                        pdfDoc.GetPage(pageNum).AddWatermark(watermarkText);
                    }

                    document.Close();
                }
            }
        }
    }
    catch (Exception ex)
    {
        valid = false;
        // Log the full exception for debugging (don't just swallow it!)
        Console.WriteLine($"Watermark failed: {ex.Message}\n{ex.StackTrace}");
    }
    return valid;
}

Critical Improvements

  • Uses Path.Combine to avoid path separator bugs (e.g., missing slashes)
  • Auto-creates the destination folder if it doesn't exist
  • using statements ensure all PDF resources are properly released (no more locked files!)
  • Added full exception handling to catch and log errors
  • Customizable watermark properties (adjust text, size, opacity as needed)

内容的提问来源于stack exchange,提问作者achmad darmawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:09