所以我正在写一个快速的应用程序,根据宽高比整齐地将我的壁纸排序到文件夹中.一切顺利,直到我尝试实际移动文件(使用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(); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。