为什么我的C#-console应用程序因复制文件时“内存不足”异常而崩溃?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么我的C#-console应用程序因复制文件时“内存不足”异常而崩溃?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2006字,纯文字阅读大概需要3分钟。
内容图文
我做了一个非常简单的程序,可以在外部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:
The file does not have a valid image format.
-or-
GDI+ does not support the pixel format of the file.
看看this
内容总结
以上是互联网集市为您收集整理的为什么我的C#-console应用程序因复制文件时“内存不足”异常而崩溃?全部内容,希望文章能够帮你解决为什么我的C#-console应用程序因复制文件时“内存不足”异常而崩溃?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。