C# upload file by webclient - c#

I uploaded a file by webclient. But upload success and response link file. But when I go to the file manager I don't have the file in my account. Why ?
This is my code.
private void btnUpload_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.Headers.Add("OurSecurityHeader", "encryptedvalue");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
wc.Headers.Add(HttpRequestHeader.Cookie, "__cfduid=d56b9e4ca0801822e9231936c70518ec91397746478931; __utma=259844498.1111893290.1397796877.1397796877.1397802609.2; __utmc=259844498; __utmz=259844498.1397796877.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); login=KimJanParkC1; xfss=g7prlsjg15zl57h4; __zlcid=%7B%22mID%22%3A%22OPdgp3o75YUWIg%22%2C%22sid%22%3A%22140417.91047.473AFH5T%22%7D; __utmb=259844498.17.10.1397802609; sthumb=500x500; _mcnc=1");
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback);
wc.UploadFileAsync(new Uri("http://img102.imagetwist.com/cgi-bin/upload.cgi?upload_id="), "POST", txtPath.Text);
}
void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
// GET DOWNLOAD LINK
MessageBox.Show("Upload Finished");
}
void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
pgbStatus.Maximum = (int)e.TotalBytesToSend;
pgbStatus.Value = (int)e.BytesSent;
label6.Text = ((int)e.BytesSent * 100) / (int)e.TotalBytesToSend + "%";
}
public void UploadFileCallback(Object sender, UploadFileCompletedEventArgs e)
{
// GET RESPOND DOWNLOAD LINK
HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
hd.LoadHtml(System.Text.Encoding.UTF8.GetString(e.Result));
txtResult.Text = hd.DocumentNode.InnerHtml;
}

In windows side:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
client.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed);
client.UploadProgressChanged += new UploadProgressChangedEventHandler(ProgressChanged);
var uri = new Uri("http://www.yoursite.com/UploadFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Completed(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show(e.Error?.Message ?? "Uploaded Successfully!");
}
private void ProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
In server side you should use WebApi:
[HttpPost]
public async Task<object> UploadFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName , file);
}
catch (Exception ex)
{
// ignored
}
return null;
}

Related

How to handle exception error 404 not found while downloading files in the backgroundworker completed event?

private void downloadFile(IEnumerable<string> urls)
{
foreach (var url in urls)
{
_downloadUrls.Enqueue(url);
}
// Starts the download
btnGetDownload.Text = "Downloading...";
btnGetDownload.Enabled = false;
progressBar1.Visible = true;
lblFileName.Visible = true;
DownloadFile();
}
private void DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
var url = _downloadUrls.Dequeue();
string FileName = System.IO.Path.GetFileName(url);
client.DownloadFileAsync(new Uri(url), #"D:\Videos\videos\" + FileName);
lblFileName.Text = url;
return;
}
// End of the download
btnGetDownload.Text = "Download Complete";
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
// handle error scenario
throw e.Error;
}
if (e.Cancelled)
{
// handle cancelled scenario
}
counter--;
lblFilesCount.Text = counter.ToString();
DownloadFile();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
private void btnGetDownload_Click(object sender, EventArgs e)
{
downloadFile(videosLinks);
}
After downloading 400 files out of 1500, I got an exception 404 not found in this line :
if (e.Error != null)
{
// handle error scenario
throw e.Error;
}
The application had to be closed.
I want to continue the download to the next file, or maybe to make something that it will try to download the same file let's say more 5 times and then if not found 5 times continue to the next file.

Access to directory & files denided after creating setup.exe with inno.setup

I create a game launcher for counter-strike 1.6... Now I have a problem when I create setup.exe for the whole game and open launcher all is good, but when I try to use any options or try to launch the game I can't because I got an error message what says that access denied to folders or files...
I created startup.exe with Inno setup!
Here are the must matter codes:
home.cs
using System;
using System.IO;
using System.Windows.Forms;
using System.Text;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2
}
private void button3_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3();
f3.ShowDialog(); // Shows Form3
}
private void button7_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
f4.ShowDialog(); // Shows Form4
}
private void button4_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://fastxhoster.com/");
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"steamlop.lop";
string cfgpath = #"cstrike/config.cfg";
FileAttributes attributes = File.GetAttributes(cfgpath);
if (File.Exists(path))
{
File.SetAttributes(cfgpath, File.GetAttributes(cfgpath) | FileAttributes.ReadOnly);
var str = File.ReadAllText(path);
System.Diagnostics.Process.Start("hl.exe", arguments: str);
}
else
{
string message = "Launch options not found. Please go into launch options and click double click Reset!!!";
string title = "Launch options error";
MessageBox.Show(message, title);
}
}
}
}
options.cs
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.IO.Compression;
namespace WindowsFormsApp1
{
public partial class Form4 : Form
{
private WebClient webClient = null;
const string basPath = #"cstrike";
public Form4()
{
InitializeComponent();
}
private void btnmdl_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var mdldir = new DirectoryInfo(#"cstrike/models");
string mdlzippath = $"{basPath}/models.zip";
string extzippath = $"{basPath}";
if (!mdldir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += MdlZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/models.zip"), $"{basPath}/models.zip");
}
else
{
foreach (FileInfo file in mdldir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in mdldir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += MdlZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/models.zip"), $"{basPath}/models.zip");
}
}
private void MdlZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/models.zip", $"{basPath}");
string mdlzippath = $"{basPath}/models.zip";
if (File.Exists(mdlzippath))
{
File.Delete(mdlzippath);
}
else
{
//do nothing
}
string message = "Models are sucessfully restored!!!";
string title = "Models restored";
MessageBox.Show(message, title);
}
private void btnsound_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var sounddir = new DirectoryInfo(#"cstrike/sound");
string soundzippath = $"{basPath}/sound.zip";
string extzippath = $"{basPath}";
if (!sounddir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += SoundZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sound.zip"), $"{basPath}/sound.zip");
}
else
{
foreach (FileInfo file in sounddir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in sounddir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += SoundZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sound.zip"), $"{basPath}/sound.zip");
}
}
private void SoundZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/sound.zip", $"{basPath}");
string soundzippath = $"{basPath}/sound.zip";
if (File.Exists(soundzippath))
{
File.Delete(soundzippath);
}
else
{
//do nothing
}
string message = "Sound are sucessfully restored!!!";
string title = "Sound restored";
MessageBox.Show(message, title);
}
private void btnspr_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var sprdir = new DirectoryInfo(#"cstrike/sprites");
string sprzippath = $"{basPath}/sprites.zip";
string extzippath = $"{basPath}";
if (!sprdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += SprZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), $"{basPath}/sprites.zip");
}
else
{
foreach (FileInfo file in sprdir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in sprdir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += SprZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), $"{basPath}/sprites.zip");
}
}
private void SprZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/sprites.zip", $"{basPath}");
string sprzippath = $"{basPath}/sprites.zip";
if (File.Exists(sprzippath))
{
File.Delete(sprzippath);
}
else
{
//do nothing
}
string message = "Sprites are sucessfully restored!!!";
string title = "Sprites restored";
MessageBox.Show(message, title);
}
private void btndlls_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var dllsdir = new DirectoryInfo(#"cstrike/dlls");
string dllzippath = $"{basPath}/dlls.zip";
string extzippath = $"{basPath}";
if (!dllsdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += DllsZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/dlls.zip"), $"{basPath}/dlls.zip");
}
else
{
foreach (FileInfo file in dllsdir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in dllsdir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += DllsZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/dlls.zip"), $"{basPath}/dlls.zip");
}
}
private void DllsZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/dlls.zip", $"{basPath}");
string dllszippath = $"{basPath}/dlls.zip";
if (File.Exists(dllszippath))
{
File.Delete(dllszippath);
}
else
{
//do nothing
}
string message = "Dlls are sucessfully restored!!!";
string title = "Dlls restored";
MessageBox.Show(message, title);
}
private void btngfx_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var gfxsdir = new DirectoryInfo(#"cstrike/gfx");
string gfxzippath = $"{basPath}/gfx.zip";
string extzippath = $"{basPath}";
if (!gfxsdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += GfxZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/gfx.zip"), $"{basPath}/gfx.zip");
}
else
{
foreach (FileInfo file in gfxsdir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in gfxsdir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += GfxZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/gfx.zip"), $"{basPath}/gfx.zip");
}
}
private void GfxZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/gfx.zip", $"{basPath}");
string gfxzippath = $"{basPath}/gfx.zip";
if (File.Exists(gfxzippath))
{
File.Delete(gfxzippath);
}
else
{
//do nothing
}
string message = "Gfx are sucessfully restored!!!";
string title = "Gfx restored";
MessageBox.Show(message, title);
}
private void btnres_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var ressdir = new DirectoryInfo(#"cstrike/resource");
string reszippath = $"{basPath}/resource.zip";
string extzippath = $"{basPath}";
if (!ressdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += ResZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/resource.zip"), $"{basPath}/resource.zip");
}
else
{
foreach (FileInfo file in ressdir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in ressdir.GetDirectories())
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += ResZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/resource.zip"), $"{basPath}/resource.zip");
}
}
private void ResZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/resource.zip", $"{basPath}");
string reszippath = $"{basPath}/resource.zip";
if (File.Exists(reszippath))
{
File.Delete(reszippath);
}
else
{
//do nothing
}
string message = "Resource are sucessfully restored!!!";
string title = "Resource restored";
MessageBox.Show(message, title);
}
private void btncfg_Click(object sender, EventArgs e)
{
string cfgpath = $"{basPath}/config.cfg";
FileAttributes attributes = File.GetAttributes(cfgpath);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(cfgpath, attributes);
Console.WriteLine("The {0} file is no longer RO.", cfgpath);
}
else
{
// Make the file RO
File.SetAttributes(cfgpath, File.GetAttributes(cfgpath) | FileAttributes.ReadOnly);
Console.WriteLine("The {0} file is now RO.", cfgpath);
}
// Is file downloading yet?
if (webClient != null)
return;
var cfgsdir = new DirectoryInfo($"{basPath}");
string cfgzippath = $"{basPath}/cfg.zip";
string extzippath = $"{basPath}";
if (!cfgsdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileCompleted += CfgZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/cfg.zip"), $"{basPath}/cfg.zip");
}
else
{
foreach (FileInfo file in cfgsdir.GetFiles("*.cfg"))
{
file.Delete();
}
foreach (DirectoryInfo dir in cfgsdir.GetDirectories("*.cfg"))
{
dir.Delete(true);
}
webClient = new WebClient();
webClient.DownloadFileCompleted += CfgZipExtract;
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/cfg.zip"), $"{basPath}/cfg.zip");
}
}
private void CfgZipExtract(object sender, AsyncCompletedEventArgs e)
{
webClient = null;
ZipFile.ExtractToDirectory($"{basPath}/cfg.zip", $"{basPath}");
string cfgzippath = $"{basPath}/cfg.zip";
string cfgpathh = $"{basPath}/config.cfg";
if (File.Exists(cfgzippath))
{
File.Delete(cfgzippath);
}
else
{
//do nothing
}
File.SetAttributes(cfgpathh, File.GetAttributes(cfgpathh) | FileAttributes.ReadOnly);
string message = "Configuration files are sucessfully restored!!!";
string title = "Configuration files restored";
MessageBox.Show(message, title);
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}
}
Thanks you in advance!
I find answer!!!
I started it using Admin rights and all works !! Thanks you anyway !

How do i cancel a backgroundworker operation and how to pause/continue a backgroundworker?

I have a button that start the backgroundworker:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
button2.Enabled = true;
}
A button to cancel the backgroundworker:
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button1.Enabled = true;
button2.Enabled = false;
}
The backgroundworker dowork.progresschanged.completed events:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStatus.Text = "Downloading Filename: " + e.UserState.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
stopwatch.Stop();
}
And last the method Parseanddownloadfiles()
private void Parseanddownloadfiles()
{
using (WebClient client = new WebClient())
{
client.DownloadFile(mainurl, path_exe + "\\page.html");
}
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.testing.com" + hrefValue;
parsedlinks.Add(url);
}
}
for (int i = 0; i < parsedlinks.Count; i++)
{
try
{
using (WebClient client = new WebClient())
{
string filename = parsedlinks[i].Substring(71);
client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
backgroundWorker1.ReportProgress(0, filename);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
The important thing now is to make the cancel to work and then if it's possible to make the pause/continue after it.
Change your method int order to check the condition inside the loops into :
private void Parseanddownloadfiles()
{
using (WebClient client = new WebClient())
{
client.DownloadFile(mainurl, path_exe + "\\page.html");
}
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.testing.com" + hrefValue;
parsedlinks.Add(url);
}
if (bgw.CancellationPending == true)
return;
}
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
string filename = parsedlinks[i].Substring(71);
client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
backgroundWorker1.ReportProgress(0, filename);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
If you need to cancel the downloads, my favorite solution would be to use some Tasks and a CancellationTokenSource.
Regards

Play a video with MediaElement and download it too

I want to play a video from the web in MediaElement and in the same time to download the video too.
I try to do it with setting Stream as the source but it won't work. It is possible to do it?
EDIT:
This is what i do for now,the problem is that i want to start playing from the start and not when i finish download the file:
public void StartDownloadFile(string aVideoUrl,string aId)
{
this.VideoUrl = aVideoUrl;
this.id = aId;
startPlaying = false;
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(this.VideoUrl));
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
#region Isolated Storage Copy Code
isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
bool checkQuotaIncrease = this.IncreaseIsolatedStorageSpace(e.Result.Length);
string VideoFile = "VideoCache\\" + this.id + ".wmv";
isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile);
long VideoFileLength = (long)e.Result.Length;
byte[] byteImage = new byte[VideoFileLength];
e.Result.Read(byteImage, 0, byteImage.Length);
isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);
#endregion
callbackFinish();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
callbackDidUpdate((double)e.ProgressPercentage);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}

ProgressBar problems while program downloading file

I have a problem with a simple updater program. It should to download archive and extract it. Well, this works fine. But i cannot overcome progressbar.
It shows at setProgressBar(progressBar1.Maximum/20) fine.
But all other changes of it's value doesn't shows at all. I can't define reason for this behavior. Could anyone help me?
UPD: It seems that e.ProgressPercentage returns always 0, and only once 100, right before download is complete.
Here is my code:
static EventWaitHandle _waitHandle = new AutoResetEvent(false);
void UpdaterForm_Shown(object sender, System.EventArgs e)
{
setProgressBar(progressBar1.Maximum/20);
UpdateProgram(address, login, password);
setProgressBar(progressBar1.Maximum);
ExecuteProgram(Path + "../" + programName + ".exe");
Application.Exit();
}
private void UpdateProgram(string pathToUpdateArchive, string login, string pass)
{
string downloadedArchive = null;
Thread downloadAsync = new Thread(() => DownloadFileFromFtp(pathToUpdateArchive, login, pass, out downloadedArchive));
downloadAsync.Name = "downloadAsync";
downloadAsync.Start();
_waitHandle.WaitOne();
ExtractFile(downloadedArchive, Path + "/../");
}
private void DownloadFileFromFtp(string address, string login, string password, out string archivePath)
{
fileName = address.Substring(address.LastIndexOf('/') + 1);
try
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(login, password);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
archivePath =Path + fileName;
wc.DownloadFileAsync(new Uri(address), archivePath);
}
catch
{
}
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
setProgressBar(e.ProgressPercentage*7/10 + 10);
}
void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
_waitHandle.Set();
}
private void setProgressBar(int value)
{
if (progressBar1.InvokeRequired)
this.BeginInvoke((MethodInvoker)delegate { progressBar1.Value = value; });
else
progressBar1.Value = value;
}

Categories