为什么会发生这种code锁定我的文件? [英] why does this code lock my files?
本文介绍了为什么会发生这种code锁定我的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
香港专业教育学院缩小到这种方法,但我不明白为什么它锁定的文件。我相信你可以使用类似
使用(东西)
{
//做的东西在这里
}
但林不知道这将A)解决这一问题或B)是正确的方式,如果它没有。
什么想法?
[的DllImport(user32.dll中,字符集= CharSet.Auto)私人静态外部的Int32 SystemParametersInfo(UInt32的动作,UInt32的uParam,串vParam,UInt32的winIni);
私人静态只读UInt32的SPI_SETDESKWALLPAPER = 0×14;
私人静态只读UInt32的SPIF_UPDATEINIFILE = 0×01;
私人静态只读UInt32的SPIF_SENDWININICHANGE = 0×02;
私人无效SetWallpaper(字符串路径)
{
尝试
{
图片imgInFile = Image.FromFile(路径);
imgInFile.Save(SAVEFILE,ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER,3,SAVEFILE,SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
抓住
{
的MessageBox.show(错误设置壁纸);
}
}
#
更新code
私人无效SetWallpaper(字符串路径)
{
如果(File.Exists(路径))
{
图片imgInFile = Image.FromFile(路径);
尝试
{
imgInFile.Save(SAVEFILE,ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER,3,SAVEFILE,SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
抓住
{
的MessageBox.show(错误设置壁纸);
}
最后
{
imgInFile.Dispose();
}
}
}
解决方案
从 MSDN :文件保持锁定状态,直到图像设置。 - 所以,是的,这应该是固定的:
使用(图片imgInFile ...){...}
(作为一个方面说明,我会收紧尝试捕捉到刚刚.Save()和/或SystemParametersInfo()调用)
Ive narrowed down to this method but i don't understand why its locking the file. I believe you could use something like
using( something)
{
//do stuff here
}
But im not sure that would A) solve the issue or B) be the correct way if it did.
any ideas?
[DllImport("user32.dll", CharSet = CharSet.Auto)]private static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);
private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;
private void SetWallpaper(string path)
{
try
{
Image imgInFile = Image.FromFile(path);
imgInFile.Save(SaveFile, ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
catch
{
MessageBox.Show("error in setting the wallpaper");
}
}
#
Updated code
private void SetWallpaper(string path)
{
if (File.Exists(path))
{
Image imgInFile = Image.FromFile(path);
try
{
imgInFile.Save(SaveFile, ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
catch
{
MessageBox.Show("error in setting the wallpaper");
}
finally
{
imgInFile.Dispose();
}
}
}
解决方案
From MSDN: "The file remains locked until the Image is disposed." - so yes, this should be fixed by:
using (Image imgInFile ...) { ... }
(As a side note, I would tighten the try catch to just the .Save() and/or SystemParametersInfo() calls)
这篇关于为什么会发生这种code锁定我的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文