如何在c#程序中修复system.outofmemoryexception [英] how to fix system.outofmemoryexception in c# program
本文介绍了如何在c#程序中修复system.outofmemoryexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
hi this is my code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Windows.Forms.VisualStyles;
using System.Configuration;
using System.IO;
//using System.IO.Packaging;
using System.Xml;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace FIlelib
{
public partial class FilelibF : Form
{
public FilelibF()
{
InitializeComponent();
scrollVal = 0;
}
string SqlStr;
SqlCommand sqlcmd;
//SqlDataReader sqldr;
DataSet DS;
string safefilename;
SqlDataAdapter pagingAdapter;
DataSet pagingDS;
int scrollVal;
public TextBox IdFileStudent = new TextBox();
public TextBox Name = new TextBox();
private void BtnNextpage_Click(object sender, EventArgs e)
{
scrollVal = scrollVal + 7;
if (scrollVal > 1000000007)
{
scrollVal = 1000000000;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, 7, "paging");
}
private void BtnPerviousPage_Click(object sender, EventArgs e)
{
scrollVal = scrollVal - 7;
if (scrollVal <= 0)
{
scrollVal = 0;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, 7, "paging");
}
private void BtnSave_Click(object sender, EventArgs e)
{
String sqlcon = "Data Source=SHADOW\\AL;Initial Catalog=Filelib;Integrated Security=True";
SqlConnection cn = new SqlConnection(sqlcon);
try
{
cn.Open();
if (TxtFileName.Text == "" || TxtFilePath.Text == "")
{
MessageBox.Show("Please Insert File or Name.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
byte[] FileData = ReadFile(TxtFilePath.Text);
SqlStr = "insert into FilelibF (FilePath,FileData,FileName,FkIdFiles,SafeFileName) ";
SqlStr = SqlStr + "values(@FilePath, @FileData,@FileName,@FkIdFiles,@SafeFileName)";
SqlCommand SqlCom = new SqlCommand(SqlStr, cn);
SqlCom.Parameters.Add(new SqlParameter("@FilePath", (object)TxtFilePath.Text));
SqlCom.Parameters.Add(new SqlParameter("@FileData", (object)FileData));
SqlCom.Parameters.Add(new SqlParameter("@FileName", (object)TxtFileName.Text));
SqlCom.Parameters.Add(new SqlParameter("@FkIdFiles", (object)IdFileStudent.Text));
SqlCom.Parameters.Add(new SqlParameter("@SafeFileName", (object)safefilename));
SqlCom.ExecuteNonQuery();
SqlCom.CommandTimeout = 1000;
cn.Close();
clear();
fillGrid();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void clear()
{
TxtFileName.Text = "";
TxtFilePath.Text = "";
}
public void fillGrid()
{
String sqlcon = "Data Source=SHADOW\\AL;Initial Catalog=Filelib;Integrated Security=True";
SqlConnection cn = new SqlConnection(sqlcon);
try
{
cn.Open();
SqlStr = "Select IdAttachBord,";
SqlStr = SqlStr + " FkIdFiles,";
SqlStr = SqlStr + " FilePath,";
SqlStr = SqlStr + " FileData,";
SqlStr = SqlStr + " FileName,";
SqlStr = SqlStr + " SafeFileName";
SqlStr = SqlStr + " from FilelibF";
SqlStr = SqlStr + " where FkIdFiles ='" + IdFileStudent.Text + "'";
SqlDataAdapter ADAP = new SqlDataAdapter(SqlStr, cn);
pagingAdapter = new SqlDataAdapter(SqlStr, cn);
pagingDS = new DataSet();
DS = new DataSet();
ADAP.Fill(DS, "FilelibF");
pagingAdapter.Fill(pagingDS, scrollVal, 7, "paging");
GridFile.DataSource = DS.Tables["FilelibF"];
GridFile.DataSource = pagingDS;
GridFile.DataMember = "paging";
GridFile.Columns[4].HeaderText = "File Name";
GridFile.Columns[0].Visible = false;
GridFile.Columns[1].Visible = false;
GridFile.Columns[2].Visible = false;
GridFile.Columns[3].Visible = false;
GridFile.Columns[5].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
//long numBytes = fInfo.Length;
long OverTwoBillionAndSome = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)OverTwoBillionAndSome);
//Close BinaryReader
br.Close();
//Close FileStream
fStream.Close();
return data;
}
private void BtnSelect_Click(object sender, EventArgs e)
{
//Ask user to select file.
OpenFileDialog dlg = new OpenFileDialog();
DialogResult dlgRes = dlg.ShowDialog();
if (dlgRes != DialogResult.Cancel)
{
//Proviaclde file path in txtFilePath text box.
TxtFilePath.Text = dlg.FileName;
safefilename = dlg.SafeFileName;
}
}
private void StudentFile_Load(object sender, EventArgs e)
{
fillGrid();
}
private void BtnDelete_Click(object sender, EventArgs e)
{
String sqlcon = "Data Source=SHADOW\\AL;Initial Catalog=Filelib;Integrated Security=True";
SqlConnection cn = new SqlConnection(sqlcon);
try
{
cn.Open();
if (GridFile.SelectedRows[0].Index != -1)
{
DialogResult dr = MessageBox.Show("Are you sure you want to delete this file?", "Confirmation",
MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
SqlStr = "Delete from FilelibF where IdAttachBord = @SelectedCell";
sqlcmd = new SqlCommand(SqlStr, cn);
sqlcmd.Parameters.Add(new SqlParameter("SelectedCell", GridFile.SelectedRows[0].Cells[0].Value));
sqlcmd.ExecuteNonQuery();
//...........................
GridFile.Rows.RemoveAt(GridFile.SelectedRows[0].Index);
}
else if (dr == DialogResult.No)
{
}
}
else
{
MessageBox.Show("Please Select a Row.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
finally
{
cn.Close();
}
}
private void BtnDisplay_Click(object sender, EventArgs e)
{
if (GridFile.CurrentCell == null)
{
MessageBox.Show("Please Select A Row.");
return;
}
DataTable dt = new DataTable();
int SelectedRow = GridFile.CurrentCell.RowIndex;
string OriginalPath = GridFile.SelectedRows[0].Cells[2].Value.ToString();
string tempsafefilename = GridFile.SelectedRows[0].Cells[5].Value.ToString();
saveFileDialog2.FileName = OriginalPath;
string FileName = saveFileDialog2.FileName;
//.......
if (File.Exists(FileName))
{
Process.Start(FileName);
}
else
{
byte[] FileData = (byte[])DS.Tables["FilelibF"].Rows[SelectedRow]["FileData"];
String newfile = @"C:\Temp";
DirectoryInfo l_dDirInfo = new DirectoryInfo(newfile);
if (l_dDirInfo.Exists == false)
{
Directory.CreateDirectory(newfile);
}
string NewPath = newfile + "\\" + tempsafefilename;
using (FileStream fs = new FileStream(NewPath, FileMode.Create))
{
fs.Write(FileData, 0, FileData.Length);
Process.Start(NewPath);
}
}
}
private void GridFile_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (GridFile.CurrentCell == null)
{
MessageBox.Show("Please Select a Row.");
return;
}
DataTable dt = new DataTable();
int SelectedRow = GridFile.CurrentCell.RowIndex;
string OriginalPath = GridFile.SelectedRows[0].Cells[2].Value.ToString();
string tempsafefilename = GridFile.SelectedRows[0].Cells[5].Value.ToString();
saveFileDialog2.FileName = OriginalPath;
string FileName = saveFileDialog2.FileName;
//.......
if (File.Exists(FileName))
{
Process.Start(FileName);
}
else
{
byte[] FileData = (byte[])DS.Tables["FilelibF"].Rows[SelectedRow]["FileData"];
String newfile = @"C:\Temp";
DirectoryInfo l_dDirInfo = new DirectoryInfo(newfile);
if (l_dDirInfo.Exists == false)
{
Directory.CreateDirectory(newfile);
}
string NewPath = newfile + "\\" + tempsafefilename;
using (FileStream fs = new FileStream(NewPath, FileMode.Create))
{
fs.Write(FileData, 0, FileData.Length);
Process.Start(NewPath);
}
当我想添加超过200MB的文件时我得到system.outofmemoryexception错误。
这是我的笔记本电脑规格:
核心i7 3GHz 4核
8gb内存1600mhz
1tb hdd
when i want to add files over 200MB i get system.outofmemoryexception error.
this is my laptop spec :
core i7 3GHz 4core
8gb ram 1600mhz
1tb hdd
推荐答案
.Net的堆内存大小有限。它与您的PC规格无关。
如果您正在阅读一个大型文本文件,那么您必须将其流式传输到我的行。
如果你要保存/加载到数据库,那么你必须将它保存在较小的块中。也许你可以将文件拆分成行或页面?
无论哪种方式,你都需要重新考虑你的方法:/
>
UPDATE:Streaming看起来是最好的选择,所以我在评论中提供了以下OP的链接:
使用C#将MSREAM VARBINARY数据传入和传出MSSQL
.Net has a limited heap memory size. It has nothing to do with your PC specs.
If you were reading a large text file then you would have to stream it line my line.
If you're saving / loading to and from a db then you will have to save it in smaller chunks. Perhaps you could split the file into lines or pages?
Either way, you will have to rethink your approach :/
UPDATE: Streaming looks like the best option so I provided the following link to the OP in the comments:
STREAM VARBINARY DATA TO AND FROM MSSQL USING C#
这篇关于如何在c#程序中修复system.outofmemoryexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文