Hello!
First, I'm sorry because of my english... I'll try to be
understandable!
I've got a strange problem using .NET 2003 C# and I haven't figured it
out for a long time. I'm implementing an application to download images
using System.NET classes (webclient, webrequest) asynchronously behind
proxy server. The reading method works like this:
System.Net.WebClient client=new System.Net.WebClient();
client.Credentials=System.Net.CredentialCache.Defa ultCredentials;
while(!isEnded)
{
webRequest=(System.Net.HttpWebRequest)System.Net.W ebRequest.Create(url);
webRequest.Credentials=System.Net.CredentialCache. DefaultCredentials;
webRequest.Timeout=10000;
webRequest.Proxy=System.Net.WebProxy.GetDefaultPro xy();
webResponse=(System.Net.HttpWebResponse)webRequest .GetResponse();
fileSize=webResponse.ContentLength;
strResponse=client.OpenRead(url);
strLocal=new
System.IO.FileStream(filename,System.IO.FileMode.C reate,System.IO.FileAccess.Write,System.IO.FileSha re.None);
downBuffer=new byte[2048];
while(strLocal.Length<fileSize)
{
strResponse.BeginRead(downBuffer,0,downBuffer.Leng th,new
System.AsyncCallback(streamreaded),strResponse);
strLocal.Write(downBuffer,0,readed);
}
strLocal.Close();
strResponse.Close();
webResponse.Close();
}
The main loop managed to download several files.
So, the problem is the following: the read method (beginread) always
hangs in time, undeterminately. It downloads some files and then
somewhere (in the middle of a download) it stops the transfer and
hangs. I've found that if I've downloaded the file using my browser
(Firefox) before, than there will be no problem with that file -
strange... The proxy is set properly. I'm getting crazy with this. If
anyone would help me, please do it!
Thanks a lot!
Kornel 2 5948
Thus wrote kkb, Hello! First, I'm sorry because of my english... I'll try to be understandable! I've got a strange problem using .NET 2003 C# and I haven't figured it out for a long time. I'm implementing an application to download images using System.NET classes (webclient, webrequest) asynchronously behind proxy server. The reading method works like this:
System.Net.WebClient client=new System.Net.WebClient();
client.Credentials=System.Net.CredentialCache.Defa ultCredentials;
while(!isEnded)
{
webRequest=(System.Net.HttpWebRequest)System.Net.W ebRequest.Create(url );
webRequest.Credentials=System.Net.CredentialCache. DefaultCredentials;
webRequest.Timeout=10000;
webRequest.Proxy=System.Net.WebProxy.GetDefaultPro xy();
webResponse=(System.Net.HttpWebResponse)webRequest .GetResponse();
fileSize=webResponse.ContentLength;
strResponse=client.OpenRead(url);
strLocal=new
System.IO.FileStream(filename,System.IO.FileMode.C reate,System.IO.File Access.Write,System.IO.FileShare.None);
downBuffer=new byte[2048];
while(strLocal.Length<fileSize)
{
strResponse.BeginRead(downBuffer,0,downBuffer.Leng th,new
System.AsyncCallback(streamreaded),strResponse);
strLocal.Write(downBuffer,0,readed);
}
strLocal.Close();
strResponse.Close();
webResponse.Close();
}
The main loop managed to download several files.
So, the problem is the following: the read method (beginread) always hangs in time, undeterminately. It downloads some files and then somewhere (in the middle of a download) it stops the transfer and hangs. I've found that if I've downloaded the file using my browser (Firefox) before, than there will be no problem with that file - strange... The proxy is set properly. I'm getting crazy with this. If anyone would help me, please do it!
You should have posted the AsyncCallback as well. Your async I/O code seems
rather weird to me... the while loop doesn' make sense, since after firing
off BeginRead(), you try to copy received data to the file stream without
ever waiting to actually receive any data.
Also, the assumption that you will always receive a Content-Length header
is wrong. In general, you should read from the response stream until you
receive no more input.
Cheers,
--
Joerg Jooss ne********@joergjooss.de
Dear Joerg Jooss!
Thanks your answer! I haven't posted my whole code, just copied out the
structure. The whole source of the download method and the
asynccallback is this:
private System.Threading.Thread thrDownload;
private System.IO.Stream strResponse;
private System.IO.Stream strLocal;
private System.Net.HttpWebRequest webRequest;
private System.Net.HttpWebResponse webResponse;
private static int PercentProgress;
private System.Boolean isEnded;
private System.Int32 readed;
private System.Threading.ManualResetEvent timermre;
private const int TTL=500;
private const int retry=5;
private const int package=2048;
private void UpdateProgress(System.Int64 BytesRead, System.Int64
TotalBytes)
{
PercentProgress=Convert.ToInt32((BytesRead*100)/TotalBytes);
progressBar1.Value=PercentProgress;
label3.Text="Downloaded "+BytesRead+" out of "+TotalBytes+"
("+PercentProgress+"%)";
}
private void Download()
{
System.String prefix="",suffix="";
System.Int32 counter=0,start=0;
System.Int64 fileSize;
if(textBox1.Text.Length<7 || (textBox1.Text.LastIndexOf('.')==-1))
{
System.Windows.Forms.MessageBox.Show(this,"Specifi ed URL is not in
a correct format! Please check it!","Wrong
URL!",System.Windows.Forms.MessageBoxButtons.OK,Sy stem.Windows.Forms.MessageBoxIcon.Warning);
button2_Click(this, new System.EventArgs());
}
else
{
try
{
start=System.Convert.ToInt32(textBox1.Text.Substri ng(textBox1.Text.Length-7,3));
}
catch(System.Exception)
{
System.Windows.Forms.MessageBox.Show(this,"Specifi ed URL is not in
a correct format! Please check it!","Wrong
URL!",System.Windows.Forms.MessageBoxButtons.OK,Sy stem.Windows.Forms.MessageBoxIcon.Warning);
button2_Click(this, new System.EventArgs());
}
counter=start;
prefix=textBox1.Text.Substring(0,textBox1.Text.Len gth-7);
suffix=textBox1.Text.Substring(textBox1.Text.Lengt h-4);
}
byte[] downBuffer;
System.Timers.Timer timer1=new System.Timers.Timer();
timer1.Interval=TTL;
timer1.Elapsed+=new System.Timers.ElapsedEventHandler(timertick);
int retnum=0;
System.Net.WebClient client=new System.Net.WebClient();
client.Credentials=System.Net.CredentialCache.Defa ultCredentials;
while(!isEnded)
{
try
{
webRequest=(System.Net.HttpWebRequest)System.Net.W ebRequest.Create(prefix+Fill(counter.ToString())+s uffix);
webRequest.Credentials=System.Net.CredentialCache. DefaultCredentials;
webRequest.Timeout=10000;
if(checkBox1.Checked)
{
webRequest.Proxy=System.Net.WebProxy.GetDefaultPro xy();
webRequest.Proxy.Credentials=System.Net.Credential Cache.DefaultCredentials;
}
/*else
webRequest.Proxy=System.Net.GlobalProxySelection.G etEmptyWebProxy();*/
webResponse=(System.Net.HttpWebResponse)webRequest .GetResponse();
if(webResponse.StatusCode==System.Net.HttpStatusCo de.OK &&
webResponse.ContentLength>3)
{
statusBar1.Text=System.String.Format("Downloading file:
{0}...",prefix+Fill(counter.ToString())+suffix);
fileSize=webResponse.ContentLength;
strResponse=client.OpenRead(prefix+Fill(counter.To String())+suffix);
strLocal=new
System.IO.FileStream(Fill(counter.ToString())+suff ix,System.IO.FileMode.Create,System.IO.FileAccess. Write,System.IO.FileShare.None);
downBuffer=new byte[package];
readed=1;
timermre=new System.Threading.ManualResetEvent(false);
while(readed>0)
{
readed=-1;
timermre.Reset();
strResponse.BeginRead(downBuffer,0,downBuffer.Leng th,new
System.AsyncCallback(streamreaded),strResponse);
timer1.Enabled=true;
timer1.Start();
timermre.WaitOne();
timer1.Stop();
timer1.Enabled=false;
if(readed<0)
++retnum;
else
{
strLocal.Write(downBuffer,0,readed);
if(strLocal.Length<=fileSize)
this.Invoke(new UpdateProgessCallback(UpdateProgress), new
object[] { strLocal.Length, fileSize });
}
}
strLocal.Close();
strResponse.Close();
}
else
button2_Click(this, new System.EventArgs());
}
catch(System.Exception ex)
{
if(System.Windows.Forms.MessageBox.Show(this,Syste m.String.Format("{0}
files successfully downloaded.\r\n\r\nDo you want to read the
terminator
message?",((System.Int32)(counter-start)).ToString()),"Download
finished...",System.Windows.Forms.MessageBoxButton s.YesNo,System.Windows.Forms.MessageBoxIcon.Inform ation)==System.Windows.Forms.DialogResult.Yes)
System.Windows.Forms.MessageBox.Show(this,ex.ToStr ing(),"Thread
last recieved
message...",System.Windows.Forms.MessageBoxButtons .OK,System.Windows.Forms.MessageBoxIcon.Informatio n);
button2_Click(this, new System.EventArgs());
}
finally
{
if(webResponse!=null)
webResponse.Close();
if(strResponse!=null)
strResponse.Close();
if(strLocal!=null)
strLocal.Close();
progressBar1.Value=0;
}
if(readed!=-1)
{
++counter;
retnum=0;
}
else if(retnum>=retry)
{
if(System.Windows.Forms.MessageBox.Show(this,"The file transfer
terminated unexpectedly. Check your
connection!","Terminated!",System.Windows.Forms.Me ssageBoxButtons.RetryCancel,System.Windows.Forms.M essageBoxIcon.Error)==System.Windows.Forms.DialogR esult.Cancel)
{
button2_Click(this,new System.EventArgs());
return;
}
else
retnum=0;
}
}
label3.Text="Stopped...";
statusBar1.Text="Ready.";
button1.Enabled=true;
}
private void timertick(System.Object sender,
System.Timers.ElapsedEventArgs e)
{
timermre.Set();
}
private void streamreaded(System.IAsyncResult ar)
{
System.IO.Stream strm=(System.IO.Stream)ar.AsyncState;
readed=strm.EndRead(ar);
timermre.Set();
}
After beginread called, the application waits until the reading ends OR
until a time (set in variable called TTL, in milisecs) expires <-
sometimes, as I've said, the transfer stops during the beginread / read
process and I thought I should retry it if it hangs for some time. As
you see, it didn't solve the problem... :(
Kornel This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Helen Abell |
last post by:
Hi,
I am trying to use a .Net WebClient object to read data
from a url, but I am getting the following error:
System.Net.HttpWebRequest.CheckFinalStatus()...
|
by: Ram Baruch |
last post by:
Hi,
I'm trying to use WebClient class to upload data. In order to upload it, I
need to use my username and password. Does somebody know how can I set it in
the WebClient class?
Regards,
Ram.
|
by: xzzy |
last post by:
I have .net 1.1
c# . . . . .
using System.Net only lists sockets
what do I need to do to be able to do:
using System.Net.WebClient;
|
by: Helen |
last post by:
Hi,
I am trying to use a .Net WebClient object to read data
from a url, but I am getting the following error:
System.Net.HttpWebRequest.CheckFinalStatus()...
|
by: galan1971 |
last post by:
Hello, I'm trying to post to a page on a remote server and retrieve the
result page and all is working fine except for one thing, the images
which are dynamically created on the remote server...
|
by: vin.dor |
last post by:
Dear All,
I am using WebClient in my Visual Studio .Net 2003 project to download
an image from the Internet. The following is my function:
C# Code:
public static bool downloadFile(string...
|
by: Mad Scientist Jr |
last post by:
For some reason I can't get a WebClient to access an outside URL from
behind our firewall. The code works when it runs outside the firewall.
I turned on windows authentication in the web.config...
|
by: MaxMax |
last post by:
Is it possible to tell to the WebClient to use an "automatic" encoding when
doing DownloadString? The encoding of the connection is written in the
header, so the WebClient should be able to sense...
|
by: MichaelSchoeler |
last post by:
Hi,
I'm having problems with the WebClient class regarding UTF-8 encoded data.
When I access a specific webservice directly I can see the data arrives in corretly formatted UTF-8. But when I...
|
by: Svinja |
last post by:
Hi, i am using WebClient.UploadFile to upload a file on my web page, code:
WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(userName, pass);...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |