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

标签 c# .net file locking wallpaper

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

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/

相关文章:

c# - 仅使用以另一个组合框中所选项目第一个字符开头的结果填充组合框

c# - 查询具有可为空 datetimetimeoffset 属性的链接实体时出现问题

c# - WCF 终结点错误 : Could not find default endpoint element

c# - 从 Windows Phone 8 的内部存储中读取?

java - 如何仅将 GET_CONTENT 用于音频?

c# - 这个测试是否正确 : if(obj1. type == obj2.type == 1)?

C# 列表排序与插入

.net - 为什么第一次执行查询需要两倍的时间?

c# - Azure DevOps 测试数据库

javascript - 使用隐藏 IFrame 在 javascript 中上传的文件的大小