Close a file handle opened by .NET

一个人想着一个人 提交于 2019-12-11 09:53:49

问题


I'm working on a script to rename files based on EXIF data.

param([string]$path)

# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null

function MakeString { 
    $s=""
    for ($i=0 ; $i -le $args[0].value.length; $i ++) {
        $s = $s + [char]$args[0].value[$i]
    }
    return $s
}

$files = Get-ChildItem -Path $path
foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)
    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}

Reading the date from EXIF is no problem, but when I try to rename the file I get this error message:

Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+     $file |Rename-Item -NewName $newFilename
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

When I monitor the directory in ProcMon I can see that the files are closed rather late:

(look at the highlighted line, it's from an earlier file in the middle of the entries from the file currently being processed)

So, how can I close the file (which is probably still open from the EXIF read) so I can rename it?

What I already tried to close the open file:

Remove-Variable exif
$file.Close()

回答1:


Since you only read from the the file, then a call to Dispose() should do the trick. Ex.

    foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)

    #Disposing object as soon as possible
    $exif.Dispose()

    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}


来源:https://stackoverflow.com/questions/28397035/close-a-file-handle-opened-by-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!