打印后删除文件

时间:2018-08-22 00:22:25

标签: c# file process

我正在使用以下代码在临时路径中创建文件,然后在成功完成打印后将其删除。但是在打印后,我尝试处理该文件,并且当我尝试删除该文件时,仍然出现异常消息:“该进程无法访问文件'Chart0.png',因为该文件正在被另一个进程使用。”请帮忙。

我也尝试过将删除代码放在finally块中,但还是没有运气。

public static bool PrintAllCharts(Dictionary<string, ILightningChartInterface> charts)
        {
            DirectoryInfo info = null;
            try
            {
                string FilePathWithoutFileName = string.Empty;
                info = Directory.CreateDirectory(@"C:\TempCharts");
                for (int i = 0; i < charts.Count; i++)
                {
                    KeyValuePair<string, ILightningChartInterface> kp = charts.ElementAt(i);
                    FilePathWithoutFileName = info.FullName;
                    string FullPath = string.Format("{0}/Chart{1}.png", FilePathWithoutFileName, i.ToString());
                    kp.Value.SaveChartToFile(FullPath);
                }
                var files = Directory.GetFiles(FilePathWithoutFileName);

                using (var pdoc = new PrintDocument())
                {
                    using (var pdi = new System.Windows.Forms.PrintDialog { Document = pdoc, UseEXDialog = true })
                    {
                        if (pdi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            pdoc.PrinterSettings = pdi.PrinterSettings;
                            pdoc.PrintPage += Pdoc_PrintPage;
                            foreach (var file in files)
                            {
                                pdoc.DocumentName = file;
                                pdoc.Print();
                            }
                        }
                    }
                }
                //Dispose the file after printing.
                foreach(var file in files)
                {
                    Image.FromFile(file).Dispose();
                    File.Delete(file); //This line gives an exception
                }

                foreach (DirectoryInfo dir in info.GetDirectories())
                {
                    dir.Delete(true);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private static void Pdoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            string file = ((PrintDocument)sender).DocumentName;
            System.Drawing.Image img = System.Drawing.Image.FromFile(file);
            Rectangle m = e.MarginBounds;

            if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
            }
            e.Graphics.DrawImage(img, m);
        }

1 个答案:

答案 0 :(得分:3)

问题出在您的### VARS ### $subdirs = "Subdir1","Subdir2","Subdir3","Subdir4" ### FUNCTIONS ### # Stole this function from https://code.adonline.id.au/folder-file-browser-dialogues-powershell/ function Find-Folders { [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() $browse = New-Object System.Windows.Forms.FolderBrowserDialog $browse.SelectedPath = "C:\" $browse.ShowNewFolderButton = $false $browse.Description = "Choose a parent directory" $loop = $true while($loop) { if ($browse.ShowDialog() -eq "OK") { $loop = $false #Insert your script here } else { $res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Would you like to try again or exit?", "Select a location", [System.Windows.Forms.MessageBoxButtons]::RetryCancel) if($res -eq "Cancel") { #Ends script return } } } $browse.SelectedPath $browse.Dispose() } # Stole this function from https://stackoverflow.com/questions/30534273/simple-inputbox-function Function Get-NewDirName (){ [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') $title = 'New Directory' $msg = 'New directory name:' [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title) } ### MAIN ### $parentDir = Find-Folders if ($parentDir) { #Get the new directory name $NewDirName = Get-NewDirName if ($NewDirName) { #Creates the parent directory New-Item -Path $parentDir\$NewDirName -ItemType Directory #A parent directory was found ForEach ($dir in $subdirs) { New-Item -Path $parentDir\$NewDirName\$dir -ItemType Directory } } else { Write-Error "No directory name was specified" } } else { Write-Error "No parent directory was specified" } 方法中。您正在使用以下行来读取文件:

Pdoc_PrintPage

System.Drawing.Image img = System.Drawing.Image.FromFile(file); 的{​​{3}}状态:

  

该文件将保持锁定状态,直到处理完图像为止。

实际上,您应该这样编写代码,以便在处理完图像后将其丢弃(并解锁文件):

FromFile

请注意,您必须处置同一图像实例。当前,您的删除循环中包含以下代码:

string file = ((PrintDocument)sender).DocumentName;
using (System.Drawing.Image img = System.Drawing.Image.FromFile(file))
{
    Rectangle m = e.MarginBounds;

    if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
    {
        m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
    }
    else
    {
        m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
    }
    e.Graphics.DrawImage(img, m);
}

那只是在尝试加载文件的第二个副本然后立即将其丢弃。完成上述更改后,还应该从删除循环中删除此行。