I am creating a new FileDownload by the following code in Form2:
public partial class Form2 : Form
{
private String location;
private Label label;
private Thread downloadA;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
location = "http://url/file.ext";
label = label2;
label.Text = "Connecting";
button1.Text = "Cancel";
downloadA = new Thread(new ThreadStart(downloadFile));
downloadA.Start();
}
private void downloadFile()
{
new FileDownload(label, location);
}
}
FileDownload.cs looks like this:
public partial class FileDownload : Form
{
private delegate void updateProgressDelegate(long downloaded, Label label);
private long fileSize;
private String path;
public FileDownload(Label label, String location)
{
try
{
WebClient client = new WebClient();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
fileSize = response.ContentLength;
Stream remote = client.OpenRead(location);
int slash = location.LastIndexOf("/");
String filename = location.Substring(slash + 1);
Stream local = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
path = Path.GetFileName(filename);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = remote.Read(buffer, 0, buffer.Length)) > 0)
{
local.Write(buffer, 0, read );
Invoke(new updateProgressDelegate(updateProgress), new object[] { local.Length, label });
}
remote.Close();
local.Close();
}
finally
{
}
}
private void updateProgress(long downloaded, Label label)
{
if (downloaded == fileSize)
{
label.Text = "Completed";
return;
}
int percentage = Convert.ToInt32(downloaded * 100 / fileSize);
label.Text = "Downloading: " + percentage + "%";
}
}
What I am attempting to do (in the above example), is to update Form2.label2 with the download percentage completed.
I keep getting the runtime error "Invoke or BeginInvoke cannot be called on a control until the window handle has been created."
I have searched various sites about this problem but couldn't find anything specific about making such changes when using another class. If I did find any information I didn't really understand it. I've only been playing about in C# for a couple of hours and prior to this, have some limited Java knowledge; I haven't covered threading yet so it's a new concept to me.
I would really appreciate any help that you would be able to give me. Thanks for your time, looking forward to hearing your answers.
Andrew