Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi this is my code :

C#
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);


                }


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
Posted
Updated 8-Jan-16 20:23pm
v2

1 solution

.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#
 
Share this answer
 
v2
Comments
brandon1999 8-Jan-16 5:14am    
i'm saving the files into a db.i'm saving movies and setup files how to split these files ?! Can you explain it more clearly?( i'm 15 years old and english is my second language )
Andy Lanng 8-Jan-16 5:50am    
I can only suggest that you don't save these to a db. Well, not using .Net anyway. You could try using compression but that may not help much either.

What you might like to look at is byte streaming where you can write the file to / from the db in a stream. That would avoid loading the entire file all at once.

I found this that should help you get started: STREAM VARBINARY DATA TO AND FROM MSSQL USING C#

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900