out of range exception when displaying images from files array.

Mar 23 2023 10:55 AM

I have array name files containing files names from the hard disk. There are 41 files in the array. The problem is in a trackBar ValueChanged event when I'm moving the slider of the trackBar to the bottom to 0 then value is -1 and it's throwing the exception beacuse I'm doing value - 1

pictureBox1.Image = Image.FromFile(files[(int)value - 1]);

and if I'm not making - 1 then it will throw the same exception when I'm moving the trackBar slider up to the last value 40.

there are 41 items in the array from 0 to 40.

this is the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using System.Xml;
using HtmlAgilityPack;
using System.Security.Policy;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace Download_Multi_Files
{
    public partial class Form1 : Form
    {
        private Dictionary<string, string> linksandtime = new();
        private List<string> links = new List<string>();
        private List<Image> images = new List<Image>();
        private string htmlCode = "";
        private string result = "";
        private string[] files;

        public Form1()
        {
            InitializeComponent();

            textProgressBar1.DisplayStyle = ProgressBarDisplayText.CustomText;
            textProgressBar1.CustomText = "0";
            GetLinks();
            macTrackBar1.Value = 0;
            GetImages();
        }

        private void GetLinks()
        {
            using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
            {
                htmlCode = client.DownloadString("somesitehere");
            }

            var linkParser = new Regex(@"\b(?:?://|\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var rawString = htmlCode;
            foreach (Match m in linkParser.Matches(rawString))
            {
                if (m.Value.EndsWith("png"))
                {
                    if (!linksandtime.ContainsValue(m.Value))
                    {
                        int index = m.Value.LastIndexOf("/");
                        int index1 = m.Value.LastIndexOf(".png");
                        if (index1 != -1)
                        {
                            result = m.Value.Substring(index + 1, index1 - index - 1);
                        }

                        if (!linksandtime.ContainsKey(result))
                        {
                            linksandtime.Add(result, m.Value);
                            links.Add(m.Value);
                        }
                    }
                }
            }
        }

        private async Task Download()
        {
            Stopwatch sw = new Stopwatch();
            for (int i = 0; i < links.Count; i++)
            {
                using (WebClient webClientTemp = new WebClient())
                {
                    webClientTemp.Proxy = null;
                    webClientTemp.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
                    webClientTemp.DownloadFileCompleted += new AsyncCompletedEventHandler(((sender, e) => WebClientTemp_DownloadFileCompleted(sender, e, sw, i)));
                    webClientTemp.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChangedTemp(sender, e, sw));

                    Uri URL = new Uri(links[i]);
                    sw.Start();


                    await webClientTemp.DownloadFileTaskAsync(URL, @"d:\testfiles\" + i.ToString() + ".png");

                }
            }
        }

        private void ProgressChangedTemp(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)
        {
            string downloadProgress = e.ProgressPercentage + "%";
            string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds).ToString("0.00"));
            string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0, 3) + " MB";
            string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0, 3) + " MB";

            // Format progress string
            string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) @ {downloadSpeed}"; // 10 MB / 100 MB (10%) @ 1.23 MB/s
            lblDownloadProgress.Text = progress;
            textProgressBar1.Value = e.ProgressPercentage;
            textProgressBar1.CustomText = progress;
        }

        private void WebClientTemp_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e, Stopwatch sw, int i)
        {
            if (e.Error == null)
            {
                sw.Stop();

                if (i == links.Count - 1)
                {
                    GetImages();
                }
            }
            else
            {
                string t = e.Error.Message;
            }
        }

        private void GetImages()
        {
            files = Directory.GetFiles(@"d:\testfiles");
            Array.Sort(files, new MyComparer());
            macTrackBar1.Maximum = files.Length;
            if (files.Length > 1)
            {
                macTrackBar1.Enabled = true;
                pictureBox1.Image = Image.FromFile(files[macTrackBar1.Value]);
                //timer1.Enabled = true;
            }
            else
            {
                macTrackBar1.Enabled = false;
                timer1.Enabled = false;
            }
        }

        private class MyComparer : IComparer<string>
        {
            [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            private static extern int StrCmpLogicalW(string psz1, string psz2);

            public int Compare(string psz1, string psz2)
            {
                return StrCmpLogicalW(psz1, psz2);
            }
        }

        private System.Drawing.Image ConvertByteArrayToImage(byte[] byteArrayIn)
        {
            using (var ms = new MemoryStream(byteArrayIn))
            {
                return System.Drawing.Image.FromStream(ms);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private async void btnStart_Click(object sender, EventArgs e)
        {
            await Download();
        }

        int counter = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (counter == links.Count - 1)
            {
                counter = 0;
            }
            pictureBox1.Image = Image.FromFile(files[counter]);

            counter++;
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            DrawRectangle(e, pictureBox1, 3, Color.Red);
        }

        public void DrawRectangle(PaintEventArgs PaintEventArgs, PictureBox Pb, int PenWidth, Color color)
        {
            Pen myPen = new Pen(color, (int)PenWidth);
            PaintEventArgs.Graphics.DrawRectangle(myPen, 0, 0, Pb.Width - 1, Pb.Height - 1);
            PaintEventArgs.Graphics.DrawLine(myPen, 0, 0, Pb.Width, 0);
            PaintEventArgs.Graphics.DrawLine(myPen, 0, Pb.Height, Pb.Width, Pb.Height);
            PaintEventArgs.Graphics.DrawLine(myPen, 0, 0, 0, Pb.Height);
            PaintEventArgs.Graphics.DrawLine(myPen, Pb.Width, 0, Pb.Width, Pb.Height);
        }

        private void macTrackBar1_ValueChanged(object sender, decimal value)
        {
            pictureBox1.Image = Image.FromFile(files[(int)value]);
        }
    }
}

I'm setting the trackBar Maximum value in the GetImages() method.  I tried there also to make files.Length - 1 or without - 1 but same behaviour as before.

I tried in the ValueChanged event to add a check , to check if value is not 0 because then value - 1 will make it -1

but then it will not display the image file at index 0 in the files array.


Answers (1)