Check out JobNimbus - CRM for Contractors and Service Professionals.
C# Download File with Progress Bar
The following is a snippet of code to download a file in a Windows Forms application using C# and the System.Net.WebClient object. This code also updates a progress bar as the file is downloaded.
First, create a new windows forms application with C# as the target language. (NOTE: This works in any .NET framework version). Add a ProgressBar to the form and a BackgroundWorker control. Also add a Button to the form. The form will look something like this:

We need some kind of background thread to update the progress bar while the file is downloaded. If we tried to update the progress bar from the main thread, out app will just hang, allowing no user input, and the progress bar would not change until the file was completely downloaded. Instead, we need to let the main thread run separately from our lengthy download operation. Set the BackgroundWorker's properties like this:

Go to the Events view of the BackgroundWorker and double click each of its events so they are auto-wired up as shown here:

Double click the button to auto-wire up the event click event and call our background worker to start running asynchronously when the button is clicked. Your code will look something like this:
private void btnTestDownload_Click(object sender, EventArgs e)
{backgroundWorker1.RunWorkerAsync();
}
In the BackgroundWorker's DoWork method, we put the code to run the download on a separate thread. The code will look something like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{ // the URL to download the file fromstring sUrlToReadFileFrom = "http://devtoolshed.googlepages.com/filezilla_download.exe";
// the path to write the file tostring sFilePathToWriteFileTo = "C:\\filezilla_download.exe";
// first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(sUrlToReadFileFrom);System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
// gets the size of the file in bytesInt64 iSize = response.ContentLength;
// keeps track of the total bytes downloaded so we can update the progress barInt64 iRunningByteTotal = 0;
// use the webclient object to download the fileusing (System.Net.WebClient client = new System.Net.WebClient())
{ // open the file at the remote URL for readingusing (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
{ // using the FileStream object, we can write the downloaded bytes to the file systemusing (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
{ // loop the stream and get the file into the byte buffer int iByteSize = 0;byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specifiedstreamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
// calculate the progress out of a base "100"double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);int iProgressPercentage = (int)(dProgressPercentage * 100);
// update the progress barbackgroundWorker1.ReportProgress(iProgressPercentage);
}
// clean up the file streamstreamLocal.Close();
}
// close the connection to the remote serverstreamRemote.Close();
}
}
}
Now implement the BackgroundWorker's ProgressChanged event to update the progress bar. NOTE: You can ONLY update the progress bar in this method. This method synchronized back with the form's main thread. If you tried to update the progress bar from the DoWork method, you would get an exception because that is not on the same thread as the form. Here's the code:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{progressBar1.Value = e.ProgressPercentage;
}
For convenience, in the result you can show a message that your file is downloaded to note that it is completely finished like this:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ MessageBox.Show("File download complete");}
Popular Articles
Last viewed:
- Data Access Layer using SqlDataReader and C# - Code Explanation
- Get the list of ODBC data source names programatically using C#
- Running Executable from a network share - Cannot access Item - Inappropriate permissions
- Performance benchmarks for ODBC vs. Oracle, MySql, SQL Server .NET Providers
- Installing Visual Studio 2008 Server Pack 1 (SP1)
- Fixing Relative Paths in C# ASP.NET When Using Url Rewriting
Recent comments
- Reply to comment - Code Samples & Tutorials
15 hours 42 min ago - thank you for sharing
2 days 11 hours ago - Great explanation and more questions
3 days 14 hours ago - Insertion of illegal Element:
4 weeks 6 days ago - Insertion of illegal Element: 32
4 weeks 6 days ago - re "But, this will NOT work."
5 weeks 6 days ago - Unable to cast COM object of t
6 weeks 2 hours ago - Saved my life
6 weeks 1 day ago - nice
8 weeks 6 days ago - good article
10 weeks 1 day ago

I get this error The remote
I get this error
The remote server returned an error: (403) Forbidden.
Another approach
Hello!
Here is an article - Show progress on long-running operations - is an article describing another approach to keep the UI responsive, starting long-running operations (like downloading) in separate thread. The approach from above mentioned article is logically similar to the current way, but without BackgroundWorker.
Very useful, but...
Hi,
thanks for this useful article!
I tried it out and encountered that you are allocating a buffersize equally to the contentlength. This means downloading huge files will eventually overload the ram. To limit the buffersize to 1024 byte, I just changed two lines:
byte[] byteBuffer = new byte[1024];
double dTotal = (double)iSize;
Now the process is running at about 5Mb of ram. instead of e.g. 500Mb when downloading such huge a file.
Regards
shyd
It is perfect
It is perfect!
Thank you very much!
Memory use
Looking at the code here this would be completely unsuitable for anything but small files since it creates a byte array the size of the file which leads to pretty bad memory use.
Good example code but for real use anyone looking at this code should implement a fixed size buffer and flush the buffer to file and reuse it to grab the next chunk of data.
In fact it would be simpler
In fact it would be simpler to use the DownloadFileAsync method in the WebClient class
http://www.csharp-examples.net/download-files/
This way has some negative effects
The user's pc can cache the file, and if you replace it with a new one on the server with the same name it will not replace it.
Very helpful
Thank u very much
Many Thanks
This codesnipet works like a charm and saved me lots of pain.
Thank you very much.
Kudos
I have been looking for a model to learn how to do this for a month. Even after posting questions to The Code Project, I haven't come accross anything that makes as muchs sense as this article.
Great job and thank you very much.
JijKgYDvBZXRZ
This is just the peerfct answer for all of us
Download progressBar1.zip
Project Run Success But problem is that when i Past or Write path in Source file at that time one error Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'.
TXLDnoMyeLVmZKXPTJT
Put in browser whetshouie.gov/blog/2010/10/19/adrienne-explains-how-college-students-are-benefiting-affordable-care-act. Lucky Adrienne. She volunteers in her community church because her parents continue to support her after they paid all her college expenses. Poor student paying off students loans (expenses another sham) has to work part-time because full-time work cannot be found in current economy and pays practically entire paycheck on coverage. This plan is a hand out to the rich.
excellent
this code work perfect....it's very use full for my project...
thnx a lot for this example
thnx a lot for this example :)) it's very usefull
the code works, but half the
the code works, but half the time it does one of the 2 things:
1) throws "Unable to read data from the transport connection: The connection was closed." at the line "iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length);"
2) background worker seems to freeze, and eventually throw the same error.
If i go one line at a time via debug, it works like a charm... it works if display a messagebox... it waits for a while intull the user cliks ok, and the code works, but if it runs at full speed... it rarely finishes.
what should i do ?
one solution would be to
one solution would be to close the stream then reopen and continue from where it left off... can anyone please show me how this would be done ?
A little problem
Using this code I have a little problem. I've followed it to the latest bit, and still it keeps jumping from 0% to 99%, and between them there is no notification, nor changes, nothing. Why is this happening?
Also forgot that cancellation
Also forgot that cancellation won't stop the process :S
Reply to comment - Code Samples & Tutorials
{
{I have|I've} been {surfing|browsing} online more than {three|3|2|4} hours today, yet I never found any interesting article like yours. {It's|It is} pretty worth enough
for me. {In my opinion|Personally|In my view}, if all {webmasters|site owners|website owners|web owners} and bloggers made good
content as you did, the {internet|net|web} will be {much more|a lot more} useful than
ever before.|
I {couldn't|could not} {resist|refrain from} commenting. {Very well|Perfectly|Well|Exceptionally well} written!|
{I will|I'll} {right away|immediately} {take hold of|grab|clutch|grasp|seize|snatch} your {rss|rss feed} as I {can not|can't} {in finding|find|to find} your {email|e-mail} subscription {link|hyperlink} or {newsletter|e-newsletter} service. Do {you have|you've} any?
{Please|Kindly} {allow|permit|let} me {realize|recognize|understand|recognise|know} {so that|in order that} I {may just|may|could} subscribe.
Thanks.|
{It is|It's} {appropriate|perfect|the best} time to make some plans for the future and {it is|it's} time to be happy.
{I have|I've} read this post and if I could I {want to|wish to|desire to} suggest you {few|some} interesting things or {advice|suggestions|tips}. {Perhaps|Maybe} you {could|can} write next articles referring to this article. I {want to|wish to|desire to} read {more|even more} things about it!|
{It is|It's} {appropriate|perfect|the best} time to make {a few|some} plans for {the future|the longer term|the long run} and {it is|it's} time to be happy. {I have|I've} {read|learn} this {post|submit|publish|put up} and if I {may just|may|could} I {want to|wish to|desire to} {suggest|recommend|counsel} you {few|some} {interesting|fascinating|attention-grabbing} {things|issues} or
{advice|suggestions|tips}. {Perhaps|Maybe} you {could|can} write {next|subsequent} articles {relating to|referring
to|regarding} this article. I {want to|wish
to|desire to} {read|learn} {more|even more}
{things|issues} {approximately|about} it!|
{I have|I've} been {surfing|browsing} {online|on-line} {more than|greater than} {three|3} hours {these days|nowadays|today|lately|as of late}, {yet|but} I {never|by no means} {found|discovered} any {interesting|fascinating|attention-grabbing} article like yours. {It's|It is} {lovely|pretty|beautiful} {worth|value|price}
{enough|sufficient} for me. {In my opinion|Personally|In
my view}, if all {webmasters|site owners|website owners|web owners} and bloggers made {just right|good|excellent} {content|content material} as {you did|you probably did}, the {internet|net|web} {will be|shall be|might be|will probably be|can be|will likely
be} {much more|a lot more} {useful|helpful} than ever before.
|
Ahaa, its {nice|pleasant|good|fastidious} {discussion|conversation|dialogue} {regarding|concerning|about|on the topic of} this {article|post|piece of writing|paragraph} {here|at this place} at this {blog|weblog|webpage|website|web site},
I have read all that, so {now|at this time} me also commenting {here|at this place}.
|
I am sure this {article|post|piece of writing|paragraph} has
touched all the internet {users|people|viewers|visitors},
its really really {nice|pleasant|good|fastidious} {article|post|piece of
writing|paragraph} on building up new {blog|weblog|webpage|website|web site}.
|
Wow, this {article|post|piece of writing|paragraph} is
{nice|pleasant|good|fastidious}, my {sister|younger sister} is analyzing {such|these|these kinds of} things,
{so|thus|therefore} I am going to {tell|inform|let know|convey} her.
|
{Saved as a favorite|bookmarked!!}, {I really like|I like|I
love} {your blog|your site|your web site|your website}!|
Way cool! Some {very|extremely} valid points! I appreciate you {writing this|penning this} {article|post|write-up} {and the|and also the|plus the} rest of the {site
is|website is} {also very|extremely|very|also really|really} good.
|
Hi, {I do believe|I do think} {this is an excellent|this is a great} {blog|website|web site|site}.
I stumbledupon it ;) {I will|I am going to|I'm going to|I may} {come back|return|revisit} {once again|yet again} {since I|since i have} {bookmarked|book marked|book-marked|saved as a favorite} it. Money and freedom {is the best|is the greatest} way to change, may you be rich and continue to {help|guide} {other people|others}.|
Woah! I'm really {loving|enjoying|digging}
the template/theme of this {site|website|blog}. It's simple, yet effective. A lot of times it's {very hard|very difficult|challenging|tough|difficult|hard}
to get that "perfect balance" between {superb usability|user friendliness|usability}
and {visual appearance|visual appeal|appearance}. I must say {that you've|you have|you've} done a {awesome|amazing|very
good|superb|fantastic|excellent|great} job with this.
{In addition|Additionally|Also}, the blog loads {very|extremely|super} {fast|quick} for me on {Safari|Internet explorer|Chrome|Opera|Firefox}.
{Superb|Exceptional|Outstanding|Excellent} Blog!|
These are {really|actually|in fact|truly|genuinely} {great|enormous|impressive|wonderful|fantastic} ideas in {regarding|concerning|about|on the topic of} blogging.
You have touched some {nice|pleasant|good|fastidious} {points|factors|things} here.
Any way keep up wrinting.|
{I love|I really like|I enjoy|I like|Everyone loves} what
you guys {are|are usually|tend to be} up too. {This sort
of|This type of|Such|This kind of} clever work and {exposure|coverage|reporting}!
Keep up the {superb|terrific|very good|great|good|awesome|fantastic|excellent|amazing|wonderful} works guys I've {incorporated||added|included} you guys to {|my|our||my personal|my own} blogroll.|
{Howdy|Hi there|Hey there|Hi|Hello|Hey}! Someone in my {Myspace|Facebook} group shared this {site|website} with us so I came to {give it a look|look it over|take a look|check it out}. I'm definitely {enjoying|loving} the information.
I'm {book-marking|bookmarking} and will be tweeting this to my followers! {Terrific|Wonderful|Great|Fantastic|Outstanding|Exceptional|Superb|Excellent} blog and {wonderful|terrific|brilliant|amazing|great|excellent|fantastic|outstanding|superb} {style and design|design and style|design}.|
{I love|I really like|I enjoy|I like|Everyone loves} what you guys {are|are usually|tend to be} up too. {This sort of|This type of|Such|This kind of} clever work and {exposure|coverage|reporting}! Keep up the {superb|terrific|very good|great|good|awesome|fantastic|excellent|amazing|wonderful} works guys I've {incorporated|added|included} you guys to {|my|our|my personal|my own} blogroll.
|
{Howdy|Hi there|Hey there|Hi|Hello|Hey} would you
mind {stating|sharing} which blog platform you're {working with|using}? I'm {looking|planning|going} to start my own blog {in
the near future|soon} but I'm having a {tough|difficult|hard} time {making a decision|selecting|choosing|deciding} between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your {design and style|design|layout} seems different then most blogs and I'm looking for something
{completely unique|unique}. P.S {My apologies|Apologies|Sorry} for {getting|being} off-topic
but I had to ask!|
{Howdy|Hi there|Hi|Hey there|Hello|Hey} would you
mind letting me know which {webhost|hosting company|web host}
you're {utilizing|working with|using}? I've loaded your blog in 3
{completely different|different} {internet browsers|web browsers|browsers} and I must say
this blog loads a lot {quicker|faster} then most. Can you {suggest|recommend} a good
{internet hosting|web hosting|hosting} provider at a {honest|reasonable|fair} price?
{Thanks a lot|Kudos|Cheers|Thank you|Many thanks|Thanks}, I appreciate it!
|
{I love|I really like|I like|Everyone loves} it {when people|when individuals|when folks|whenever people} {come
together|get together} and share {opinions|thoughts|views|ideas}.
Great {blog|website|site}, {keep it up|continue
the good work|stick with it}!|
Thank you for the {auspicious|good} writeup. It in fact was a
amusement account it. Look advanced to {far|more} added
agreeable from you! {By the way|However}, how {can|could} we communicate?
|
{Howdy|Hi there|Hey there|Hello|Hey} just wanted to give
you a quick heads up. The {text|words} in
your {content|post|article} seem to be running off the screen in {Ie|Internet explorer|Chrome|Firefox|Safari|Opera}.
I'm not sure if this is a {format|formatting} issue or something to do with {web browser|internet browser|browser} compatibility but I {thought|figured} I'd post to let you
know. The {style and design|design and style|layout|design} look great though!
Hope you get the {problem|issue} {solved|resolved|fixed} soon.
{Kudos|Cheers|Many thanks|Thanks}|
This is a topic {that is|that's|which is} {close to|near to} my heart... {Cheers|Many thanks|Best wishes|Take care|Thank you}! {Where|Exactly where} are your contact details though?|
It's very {easy|simple|trouble-free|straightforward|effortless} to find
out any {topic|matter} on {net|web} as compared to {books|textbooks},
as I found this {article|post|piece of writing|paragraph} at this {website|web site|site|web page}.
|
Does your {site|website|blog} have a contact
page? I'm having {a tough time|problems|trouble} locating it but, I'd like to {send|shoot} you an
{e-mail|email}. I've got some {creative ideas|recommendations|suggestions|ideas} for your blog you might be interested in hearing. Either way, great {site|website|blog} and I look forward to seeing it {develop|improve|expand|grow} over time.|
{Hola|Hey there|Hi|Hello|Greetings}! I've
been {following|reading} your {site|web site|website|weblog|blog} for {a long time|a
while|some time} now and finally got the {bravery|courage} to go ahead and
give you a shout out from {New Caney|Kingwood|Huffman|Porter|Houston|Dallas|Austin|Lubbock|Humble|Atascocita} {Tx|Texas}!
Just wanted to {tell you|mention|say} keep up the {fantastic|excellent|great|good} {job|work}!
|
Greetings from {Idaho|Carolina|Ohio|Colorado|Florida|Los angeles|California}!
I'm {bored to tears|bored to death|bored} at work so I decided to {check out|browse} your {site|website|blog} on my iphone during lunch break. I {enjoy|really like|love} the {knowledge|info|information} you {present|provide} here and can't
wait to take a look when I get home. I'm {shocked|amazed|surprised} at how {quick|fast} your blog loaded on my {mobile|cell phone|phone} .. I'm not even using WIFI,
just 3G .. {Anyhow|Anyways}, {awesome|amazing|very good|superb|good|wonderful|fantastic|excellent|great} {site|blog}!
|
Its {like you|such as you} {read|learn} my {mind|thoughts}!
You {seem|appear} {to understand|to know|to grasp} {so much|a
lot} {approximately|about} this, {like you|such as you} wrote the {book|e-book|guide|ebook|e book} in it or something.
{I think|I feel|I believe} {that you|that you simply|that you just}
{could|can} do with {some|a few} {%|p.c.|percent}
to {force|pressure|drive|power} the message {house|home} {a bit|a
little bit}, {however|but} {other than|instead of} that, {this
is|that is} {great|wonderful|fantastic|magnificent|excellent} blog.
{A great|An excellent|A fantastic} read. {I'll|I will} {definitely|certainly} be back.|
I visited {multiple|many|several|various} {websites|sites|web sites|web pages|blogs} {but|except|however} the audio {quality|feature} for audio songs {current|present|existing} at this {website|web site|site|web page} is {really|actually|in fact|truly|genuinely} {marvelous|wonderful|excellent|fabulous|superb}.|
{Howdy|Hi there|Hi|Hello}, i read your blog {occasionally|from time to time} and i own a similar one and i was just {wondering|curious} if you get a lot of spam {comments|responses|feedback|remarks}? If so how do you {prevent|reduce|stop|protect against} it, any plugin or anything you can {advise|suggest|recommend}? I get so much lately it's driving me {mad|insane|crazy} so any {assistance|help|support} is very much appreciated.
|
Greetings! {Very helpful|Very useful} advice {within this|in this
particular} {article|post}! {It is the|It's the} little changes {that make|which will make|that produce|that will make} {the biggest|the largest|the greatest|the most important|the most significant} changes. {Thanks a lot|Thanks|Many thanks} for sharing!|
{I really|I truly|I seriously|I absolutely} love {your blog|your site|your website}.. {Very nice|Excellent|Pleasant|Great} colors & theme. Did you {create|develop|make|build} {this website|this site|this web site|this amazing site} yourself? Please reply back as I'm {looking to|trying to|planning to|wanting to|hoping to|attempting
to} create {my own|my very own|my own personal} {blog|website|site} and {would like to|want
to|would love to} {know|learn|find out} where you got this from or {what the|exactly what
the|just what the} theme {is called|is named}. {Thanks|Many thanks|Thank
you|Cheers|Appreciate it|Kudos}!|
{Hi there|Hello there|Howdy}! This {post|article|blog post} {couldn't|could not} be written {any better|much better}! {Reading through|Looking at|Going through|Looking through} this {post|article} reminds me of my previous roommate! He {always|constantly|continually} kept {talking about|preaching about} this. {I will|I'll|I am going to|I most certainly will} {forward|send} {this article|this information|this post} to him.
{Pretty sure|Fairly certain} {he will|he'll|he's going
to} {have a good|have a very good|have a great} read.
{Thank you for|Thanks for|Many thanks for|I appreciate you for} sharing!
|
{Wow|Whoa|Incredible|Amazing}! This blog looks
{exactly|just} like my old one! It's on a {completely|entirely|totally} different {topic|subject} but it has pretty much the same {layout|page layout} and design. {Excellent|Wonderful|Great|Outstanding|Superb} choice of colors!|
{There is|There's} {definately|certainly} {a lot to|a great
deal to} {know about|learn about|find out about} this {subject|topic|issue}.
{I like|I love|I really like} {all the|all of the} points {you made|you've made|you have made}.|
{You made|You've made|You have made} some {decent|good|really good} points
there. I {looked|checked} {on the internet|on the web|on the
net} {for more info|for more information|to find
out more|to learn more|for additional information} about the issue and found {most individuals|most people} will go along with your views on {this
website|this site|this web site}.|
{Hi|Hello|Hi there|What's up}, I {log on to|check|read} your {new stuff|blogs|blog} {regularly|like every week|daily|on a regular basis}. Your {story-telling|writing|humoristic} style is {awesome|witty}, keep {doing what you're doing|up the good work|it up}!
|
I {simply|just} {could not|couldn't} {leave|depart|go away} your {site|web site|website} {prior to|before} suggesting that I {really|extremely|actually} {enjoyed|loved} {the standard|the usual} {information|info} {a person|an individual} {supply|provide} {for your|on your|in your|to your} {visitors|guests}? Is {going to|gonna} be {back|again} {frequently|regularly|incessantly|steadily|ceaselessly|often|continuously} {in order to|to} {check up on|check out|inspect|investigate cross-check} new posts|
{I wanted|I needed|I want to|I need to} to thank you for this {great|excellent|fantastic|wonderful|good|very good} read!! I {definitely|certainly|absolutely} {enjoyed|loved} every {little bit of|bit of} it. {I have|I've got|I
have got} you {bookmarked|book marked|book-marked|saved as
a favorite} {to check out|to look at} new {stuff you|things you} post厊
My weblog ... Tammy
cancellation
this is a little late, but here's my two cents!
you need to set the 'WorkerSupportsCancellation' property of the background worker to true, then implement some sort of button that will call the 'CancelAsync' method of the background worker, this sets the 'CancellationPending' property of the background worker to true. you then need to implement some sort of check to catch the change (if statements work well) and cancel the background worker there using the event arguments (in most cases, e.cancel works. remember to close any streams you have open! i think, but i'm not 100% sure, that if you implement the check inside a while loop you also need a break statement)
hope that helps! might be an easier way of doing it, but this works well for me. only been using c# for a few months, be happy to hear any better ways if there are any!
cracking article btw, i adapted this code for an ftp uploader and it worked a treat!
go
go
progress bar & XmlReader
Could I use this or any similiar technique with XmlReader?
Strange problem concerning the progress bar update
I created a new project (VS 2008, .Net 3.5) like shown here. Everything is working fine except the MessageBox "File download complete" is shown when the progess bar is at approximately 30 %. This seems to be a timing issue because when I debug the process and have a breakpoint in "backgroundWorker1_ProgressChanged", the progress bar is updated fine. A "progressBar1.Update();" doesn´t make any difference. Any help is appreciated.
Possible fix
I think I found the problem here, it occurs when the progress percentage is cast from a double to an int. Replace:
int iProgressPercentage = (int)dProgressPercentage * 100);
with
int iProgressPercentage = (int)(Math.Round(dProgressPercentage) * 100);
And it seems to work much better! Hope this helps
Oops
Spoke too soon, just checked it now and it's rubbish, ignore that haha
The only way this could happen
The only way this could be happening is if your download is failing early and exiting with a success case. This could be due to network traffic or some other issue. Make sure you did not accidently put a message box into your worker thread. Then make sure there are no early outs in your code that could cause it to finish at 30%.
Worked smoothly
Thanks for posting such a wonderful information. It was a perfect solution for my problem.
Thanks
Nice helpful, working post. Thanks.
Change the buffer type to long instead of int
90% sure that the issue with the arithmetic operation is because the file size is bigger than the Int32 size. Just change the buffer to a long (Int64) and try it again.
arithmetic operation resulted in an overflow
This works fine with small file but trying to download a bigger file (75MBs) i get an "arithmetic operation resulted in an overflow" exception..
any idea how to solve this?
thanks
Hiiii
Please give sample source code
What an article
Marvellous.......................
Streaming a large file from the hard drive
This code above is interested in only downloading a file from the web. To read in a large file from your hard drive such as a very large XML file, probably the best way to do this is using the FileStream object. You can find out more about it here:
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx
This will allow you to stream the file in one character at a time. Inside your loop that reads the file, you can update your progress bar and update your TreeView control.
NOTE: Make sure you are doing all of this streaming on a separate thread such as a background worker process. That way, your UI will update. If you run this streaming on your main thread, you will not see the progress bar or any other UI update and it will appear to "hang" until your file is completely streamed in.
hi thx for the code it work
hi thx for the code it work ok
but how to catch download errors when the file does not exists or no internet connection avaiable?
Catching download errors
There are a couple of ways to do this. If you attempt to download a file that does not exist (invalid URL) or that may have a connection drop/timeout, then there can be an exception thrown here.
If you want the code to prompt the user and let them retry, then put a try/catch block around the code in the background worker DoWork method. When the exception is thrown, allow them to restart the download with a dialog or other message box.
If you want to abort the operation, then you don't have to do anything because the background worker already handles exception packaging across threads for you. Just let the exception get thrown. Then in the background worker RunWorkerCompleted() method, you can get the result by checking the "e" RunWorkerCompletedEventArgs parameter. Check if the Error property is = null or not. If it is not null, then there will be the exception which you can display to the user there.
To download file from hard drive using progress bar & Background
Hi,
I have created a project to load xml file in Treeview in winform.
Now i want to add a progress bar which will show the time taken to get file from my memory to treeview.i want to use a background worker also.
I have treeview,Browse button(to select a file), textbox(to display the file name selected)
toolStripStatusLabel,toolStripStatusProgressBar.
Can you please help out..
This is very helpful article
Mine progressbar moves upto 6 count and then nothing else works. I have tried timer method, and other progress bar invalidate method. But from al these i have similar method. I cannot put background thread. Its very complex code and i cant change in between. Is there any other possible solution to update progressbar using the same main thread?
Update ProgressBar from main thread
Updating controls from your same thread during blocking operations like downloading a file will never work as well as a separate thread. You should really get into the habit of doing the updating from separate threads because this is core to doing advanced windows programming.
All of that being said, I did find a thread where you can create a delegate back to your thread that may work for you. Here is the post:
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/093dfdb2-e...
Cross-thread operation not valid
Cross-thread operation not valid
async????
async