为什么我的C#-console应用程序因复制文件时“内存不足”异常而崩
发布时间:2020-12-15 23:49:14 所属栏目:百科 来源:网络整理
导读:我做了一个非常简单的程序,可以在外部HDD上找到图片,并将它们放入文件夹中. 这听起来很简单,但出于某种原因,我在这样做的时候得到了“Out of Memory”异常. 我已经在64位Win10上测试了4 GB的内存,64位的Win10和32 GB的内存.然而,我仍然在两个系统上都获得了
我做了一个非常简单的程序,可以在外部HDD上找到图片,并将它们放入文件夹中.
这听起来很简单,但出于某种原因,我在这样做的时候得到了“Out of Memory”异常. 我已经在64位Win10上测试了4 GB的内存,64位的Win10和32 GB的内存.然而,我仍然在两个系统上都获得了“Out of Memory”特例. 我的平台目标是x64. 这是发生错误的代码: string[] filePaths = Directory.GetFiles(Stien,"*.*",SearchOption.AllDirectories); foreach (string file in filePaths) { string[] TempValue1 = file.Split(new[] { @"" },StringSplitOptions.None); string FileName = TempValue1[TempValue1.Length - 1]; if (FileName.Contains(S?geTerm)) //Checks if the name contains the search-term. { if (!SortDate) //If the program was told not to sort by date. { try { File.Copy(file,destination + @"" + FileName,true); Console.WriteLine(FileName + " => " + destination + @"" + FileName); } catch (Exception e) { Console.WriteLine("Fejl: " + e.ToString()); } } else { Image Billede = Bitmap.FromFile(file); string date; try { PropertyItem propItem = Billede.GetPropertyItem(36867); date = r.Replace(Encoding.UTF8.GetString(propItem.Value),"-",2); date = date.Split(new[] { ' ' },StringSplitOptions.None)[0]; propItem = null; } catch { date = "UKENDT"; } // if (!Directory.Exists(destination + @"" + date)) { Directory.CreateDirectory(destination + @"" + date); Console.WriteLine(destination + @"" + date); } File.Copy(file,destination + @"" + date + @"" + FileName,true); //Copies the file,and places it into the fitting folder. Console.WriteLine(FileName + " => " + destination + @"" + "" + date + @"" + FileName); date = null; //I thought this might helped clearing some memory. Billede = null; } } } 所以我的问题:导致异常的原因是什么,我该如何解决? 解决方法
如其他答案中所述,您可以使用
using statement以正确的方式在对象上调用Dispose方法.
using (Image Billede = Bitmap.FromFile(file)){ ... } 但是,对于您的代码,您可能需要检查图像格式,因为如果(来自MSDN),Image.FromFile函数将抛出OutOfMemoryException:
看看this (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |