gpt4 book ai didi

c# - 为什么这段代码会锁定我的文件?

转载 作者:太空狗 更新时间:2023-10-29 22:11:38 24 4
gpt4 key购买 nike

我已经缩小到这种方法,但我不明白为什么它会锁定文件。我相信你可以使用类似的东西

using( something)
{

//do stuff here
}

但我不确定这是否会 A) 解决问题或 B) 是否是正确的方法。

有什么想法吗?

[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");
}
}
#

更新代码

 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();
}
}
}

最佳答案

来自 MSDN :“文件将保持锁定状态,直到图像被处理掉。” - 所以是的,这应该通过以下方式解决:

using (Image imgInFile ...) { ... }

(作为旁注,我会将 try catch 收紧到仅调用 .Save() 和/或 SystemParametersInfo())

关于c# - 为什么这段代码会锁定我的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/805041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com