why does this code lock my files?

左心房为你撑大大i 提交于 2019-12-04 08:37:54

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)

HVS

Once you pass out of the using block, all objects initialized within it are disposed. In your case, the objects will be disposed which will remove the lock on the file.

You must manually dispose (either through a using statement or by calling .Dispose() on the object) any unmanaged calls to either COM or Windows API functions (i.e. when you use interop).

Crash893

Here is what i have please let me know if you see anything that i could pretty up. But its working like a champ so i'm pretty happy.

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

                    Else
                    {
                          messagebox.show("Error with path: "+path+" Not found or in use");
                    }
                }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!