简体   繁体   中英

Writing temp files

I am currently trying to display the sharepoint thumbnail in a picturebox when i click a button on the form. What appears to be happening is the file is locked and will not let me replace the file or anything. I even created a counter so the file name is always different. When I run the first time everything works, after that I believe it cant write over the file. Am I doing something wrong is there a better method??


$User=GET-ADUser $UserName –properties thumbnailphoto

$Filename='C:\Support\Export'+$Counterz+'.jpg'

#$img = $Filename.Open( [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read )

[System.Io.File]::WriteAllBytes($Filename, $User.Thumbnailphoto)

$Picture = (get-item ($Filename))

$img = [System.Drawing.Image]::Fromfile($Picture)

$pictureBox.Width =  $img.Size.Width

$pictureBox.Height =  $img.Size.Height

$pictureBox.Image = $img

$picturebox.dispose($Filename)

Remove-Item $Filename

You should be able to do this without creating a temporary file.

Just create $img like:

$img = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]::new($User.thumbnailPhoto))
$pictureBox.Width  = $img.Width
$pictureBox.Height = $img.Height
$pictureBox.Image  = $img

Don't forget to remove the form from memory after closing with $form.Dispose()


If you insist on using a temporary file, then be aware that the $img object keeps a reference to the file untill it is disposed of.

Something like:

# get a temporary file name
$Filename = [System.IO.Path]::GetTempFileName()
[System.IO.File]::WriteAllBytes($Filename, $User.thumbnailPhoto)

# get an Image object using the data from the temporary file
$img = [System.Drawing.Image]::FromFile($Filename)

$pictureBox.Width  = $img.Width
$pictureBox.Height = $img.Height
$pictureBox.Image  = $img

$form.Controls.Add($pictureBox)
$form.ShowDialog()

# here, when all is done and the form is no longer needed, you can
# get rid of the $img object that still has a reference to the
# temporary file and then delete that file.
$img.Dispose()
Remove-Item $Filename

# clean up the form aswell
$form.Dispose()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM