ASalameh
ASalameh

Reputation: 803

Calling Image.FromFile throws Out of memory exception

I have a function that fill data grid view and this function use paging

page size = 30

It's work fine until page 9 throw out of memory exception

I have windows server 2008 R2 64 bit,8 GB RAM

public static void FillDataGrid(DataGridView dataGrid, int intPageSize, int intPageIndex, out int intTotal
        ,string title)
    {

         dataGrid.Rows.Clear();

        try
        {
            var dt = GetData(intPageSize, intPageIndex, out intTotal, title); //dt type DataTable
            var dicrectory = Directory.GetCurrentDirectory();

            for (var i = 0; i < dt.Rows.Count; i++)
            {
                    var uri = new Uri(dt.Rows[i]["URL"].ToString());
                    var host = uri.Host.Replace("www.", "");
                    host = host.Replace(".com", "");

                    var iconFullUrl = dicrectory + @"\Icons\" +
                                      dt.Rows[i]["IconURL"].ToString();
                    object[] row = new object[10];
                    row[0] = "False";
                    row[1] = Image.FromFile(iconFullUrl);
                    row[2] = dt.Rows[i]["Title"].ToString();
                    row[3] = host;
                    row[4] = Convert.ToDateTime(dt.Rows[i]["Date"].ToString()).ToShortDateString();
                    row[5] = "";
                    row[6] = dt.Rows[i]["URL"].ToString();
                    row[7] = "";
                    row[8] = "";
                    row[9] = dt.Rows[i]["Id"].ToString();

                    dataGrid.Rows.Add(row);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

in this section of code the error occur

 row[1] = Image.FromFile(iconFullUrl); 

Upvotes: 1

Views: 1307

Answers (1)

Mark Hall
Mark Hall

Reputation: 54532

Adding my Comment as an Answer:

According to MSDN the OutOfMemory error can be caused by the file not having a valid image format or because GDI+ does not support the pixel format of the file.

Also as long as the image is not disposed the file will be marked as inuse

Upvotes: 2

Related Questions