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

Cra*_*893 5 .net c# locking file wallpaper

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

using( something)
{

//do stuff here
}
Run Code Online (Sandbox Code Playgroud)

但我不确定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");
        }
    }
Run Code Online (Sandbox Code Playgroud) #

更新的代码

 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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sim*_*han 15

来自MSDN:"文件保持锁定,直到图像被丢弃." - 所以是的,这应该通过以下方式解决:

using (Image imgInFile ...) { ... }
Run Code Online (Sandbox Code Playgroud)

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