c#-4.0 – 如何告诉我的C#应用??程序关闭它在FileInfo对象或可能
发布时间:2020-12-15 21:14:24 所属栏目:百科 来源:网络整理
导读:所以我正在写一个快速的应用程序,根据宽高比整齐地将我的壁纸排序到文件夹中.一切顺利,直到我尝试实际移动文件(使用FileInfo.MoveTo()).该应用程序抛出异常: System.IO.IOException 该进程无法访问该文件,因为该文件正由另一个进程使用. 唯一的问题是,我的
所以我正在写一个快速的应用程序,根据宽高比整齐地将我的壁纸排序到文件夹中.一切顺利,直到我尝试实际移动文件(使用FileInfo.MoveTo()).该应用程序抛出异常:
System.IO.IOException 唯一的问题是,我的计算机上没有其他进程正在打开该特定文件.我想也许是因为我使用该文件的方式,也许某个内部系统子程序在不同的线程上或某些东西在我尝试移动它时打开了文件.果然,在上面几行,我设置了一个属性,调用一个打开文件进行读取的事件.我假设至少有一些是异步发生的.反正它是否同步运行?我必须更改该属性或重写大部分代码. 这里有一些相关的代码,请原谅蹩脚的Visual C#默认名称,这不是真正的发布质量软件: private void button1_Click(object sender,EventArgs e) { for (uint i = 0; i < filebox.Items.Count; i++) { if (!filebox.GetItemChecked((int)i)) continue; //This calls the selectedIndexChanged event to change the 'selectedImg' variable filebox.SelectedIndex = (int)i; if (selectedImg == null) continue; Size imgAspect = getImgAspect(selectedImg); //This is gonna be hella hardcoded for now //In the future this should be changed to be generic //and use some kind of setting schema to determine //the sort/filter results FileInfo file = ((FileInfo)filebox.SelectedItem); if (imgAspect.Width == 8 && imgAspect.Height == 5) { finalOut = outPath + "8x5" + file.Name; } else if (imgAspect.Width == 5 && imgAspect.Height == 4) { finalOut = outPath + "5x4" + file.Name; } else { finalOut = outPath + "Other" + file.Name; } //Me trying to tell C# to close the file selectedImg.Dispose(); previewer.Image = null; //This is where the exception is thrown file.MoveTo(finalOut); } } //The suspected event handler private void filebox_SelectedIndexChanged(object sender,EventArgs e) { FileInfo selected; if (filebox.SelectedIndex >= filebox.Items.Count || filebox.SelectedIndex < 0) return; selected = (FileInfo)filebox.Items[filebox.SelectedIndex]; try { //The suspected line of code selectedImg = new Bitmap((Stream)selected.OpenRead()); } catch (Exception) { selectedImg = null; } if (selectedImg != null) previewer.Image = ResizeImage(selectedImg,previewer.Size); else previewer.Image = null; } 我有一个长期的修复(无论如何这可能更有效)但它仍然存在更多问题:/ 任何帮助将不胜感激. 解决方法
由于您使用selectedImg作为类范围变量,因此在打开位图时会对文件保持锁定.我会使用
using statement 然后
Clone 将Bitmap放入您正在使用的变量中,这将释放Bitmap保留在文件上的锁定.
像这样的东西. using ( Bitmap img = new Bitmap((Stream)selected.OpenRead())) { selectedImg = (Bitmap)img.Clone(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |