mscorlib(4.0.0.0) API with additions
WebClient.cs
4 using System.IO;
5 using System.Net.Cache;
7 using System.Security;
9 using System.Text;
10 using System.Threading;
11 using System.Threading.Tasks;
12 
13 namespace System.Net
14 {
16  [ComVisible(true)]
17  public class WebClient : Component
18  {
19  private class ProgressData
20  {
21  internal long BytesSent;
22 
23  internal long TotalBytesToSend = -1L;
24 
25  internal long BytesReceived;
26 
27  internal long TotalBytesToReceive = -1L;
28 
29  internal bool HasUploadPhase;
30 
31  internal void Reset()
32  {
33  BytesSent = 0L;
34  TotalBytesToSend = -1L;
35  BytesReceived = 0L;
36  TotalBytesToReceive = -1L;
37  HasUploadPhase = false;
38  }
39  }
40 
41  private class DownloadBitsState
42  {
43  internal WebClient WebClient;
44 
45  internal Stream WriteStream;
46 
47  internal byte[] InnerBuffer;
48 
49  internal AsyncOperation AsyncOp;
50 
51  internal WebRequest Request;
52 
53  internal CompletionDelegate CompletionDelegate;
54 
55  internal Stream ReadStream;
56 
57  internal ScatterGatherBuffers SgBuffers;
58 
59  internal long ContentLength;
60 
61  internal long Length;
62 
63  internal int Offset;
64 
65  internal ProgressData Progress;
66 
67  internal bool Async => AsyncOp != null;
68 
69  internal DownloadBitsState(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp, ProgressData progress, WebClient webClient)
70  {
71  WriteStream = writeStream;
72  Request = request;
73  AsyncOp = asyncOp;
74  CompletionDelegate = completionDelegate;
75  WebClient = webClient;
76  Progress = progress;
77  }
78 
79  internal int SetResponse(WebResponse response)
80  {
81  ContentLength = response.ContentLength;
82  if (ContentLength == -1 || ContentLength > 65536)
83  {
84  Length = 65536L;
85  }
86  else
87  {
88  Length = ContentLength;
89  }
90  if (WriteStream == null)
91  {
92  if (ContentLength > int.MaxValue)
93  {
94  throw new WebException(SR.GetString("net_webstatus_MessageLengthLimitExceeded"), WebExceptionStatus.MessageLengthLimitExceeded);
95  }
96  SgBuffers = new ScatterGatherBuffers(Length);
97  }
98  InnerBuffer = new byte[(int)Length];
99  ReadStream = response.GetResponseStream();
100  if (Async && response.ContentLength >= 0)
101  {
102  Progress.TotalBytesToReceive = response.ContentLength;
103  }
104  if (Async)
105  {
106  if (ReadStream == null || ReadStream == Stream.Null)
107  {
108  DownloadBitsReadCallbackState(this, null);
109  }
110  else
111  {
112  ReadStream.BeginRead(InnerBuffer, Offset, (int)Length - Offset, DownloadBitsReadCallback, this);
113  }
114  return -1;
115  }
116  if (ReadStream == null || ReadStream == Stream.Null)
117  {
118  return 0;
119  }
120  return ReadStream.Read(InnerBuffer, Offset, (int)Length - Offset);
121  }
122 
123  internal bool RetrieveBytes(ref int bytesRetrieved)
124  {
125  if (bytesRetrieved > 0)
126  {
127  if (WriteStream != null)
128  {
129  WriteStream.Write(InnerBuffer, 0, bytesRetrieved);
130  }
131  else
132  {
133  SgBuffers.Write(InnerBuffer, 0, bytesRetrieved);
134  }
135  if (Async)
136  {
137  Progress.BytesReceived += bytesRetrieved;
138  }
139  if (Offset != ContentLength)
140  {
141  if (Async)
142  {
143  WebClient.PostProgressChanged(AsyncOp, Progress);
144  ReadStream.BeginRead(InnerBuffer, Offset, (int)Length - Offset, DownloadBitsReadCallback, this);
145  }
146  else
147  {
148  bytesRetrieved = ReadStream.Read(InnerBuffer, Offset, (int)Length - Offset);
149  }
150  return false;
151  }
152  }
153  if (Async)
154  {
155  if (Progress.TotalBytesToReceive < 0)
156  {
157  Progress.TotalBytesToReceive = Progress.BytesReceived;
158  }
159  WebClient.PostProgressChanged(AsyncOp, Progress);
160  }
161  if (ReadStream != null)
162  {
163  ReadStream.Close();
164  }
165  if (WriteStream != null)
166  {
167  WriteStream.Close();
168  }
169  else if (WriteStream == null)
170  {
171  byte[] array = new byte[SgBuffers.Length];
172  if (SgBuffers.Length > 0)
173  {
174  BufferOffsetSize[] buffers = SgBuffers.GetBuffers();
175  int num = 0;
176  foreach (BufferOffsetSize bufferOffsetSize in buffers)
177  {
178  Buffer.BlockCopy(bufferOffsetSize.Buffer, 0, array, num, bufferOffsetSize.Size);
179  num += bufferOffsetSize.Size;
180  }
181  }
182  InnerBuffer = array;
183  }
184  return true;
185  }
186 
187  internal void Close()
188  {
189  if (WriteStream != null)
190  {
191  WriteStream.Close();
192  }
193  if (ReadStream != null)
194  {
195  ReadStream.Close();
196  }
197  }
198  }
199 
200  private class UploadBitsState
201  {
202  private int m_ChunkSize;
203 
204  private int m_BufferWritePosition;
205 
206  internal WebClient WebClient;
207 
208  internal Stream WriteStream;
209 
210  internal byte[] InnerBuffer;
211 
212  internal byte[] Header;
213 
214  internal byte[] Footer;
215 
216  internal AsyncOperation AsyncOp;
217 
218  internal WebRequest Request;
219 
220  internal CompletionDelegate UploadCompletionDelegate;
221 
222  internal CompletionDelegate DownloadCompletionDelegate;
223 
224  internal Stream ReadStream;
225 
226  internal long Length;
227 
228  internal int Offset;
229 
230  internal ProgressData Progress;
231 
232  internal bool FileUpload => ReadStream != null;
233 
234  internal bool Async => AsyncOp != null;
235 
236  internal UploadBitsState(WebRequest request, Stream readStream, byte[] buffer, int chunkSize, byte[] header, byte[] footer, CompletionDelegate uploadCompletionDelegate, CompletionDelegate downloadCompletionDelegate, AsyncOperation asyncOp, ProgressData progress, WebClient webClient)
237  {
238  InnerBuffer = buffer;
239  m_ChunkSize = chunkSize;
240  m_BufferWritePosition = 0;
241  Header = header;
242  Footer = footer;
243  ReadStream = readStream;
244  Request = request;
245  AsyncOp = asyncOp;
246  UploadCompletionDelegate = uploadCompletionDelegate;
247  DownloadCompletionDelegate = downloadCompletionDelegate;
248  if (AsyncOp != null)
249  {
250  Progress = progress;
251  Progress.HasUploadPhase = true;
252  Progress.TotalBytesToSend = ((request.ContentLength < 0) ? (-1) : request.ContentLength);
253  }
254  WebClient = webClient;
255  }
256 
257  internal void SetRequestStream(Stream writeStream)
258  {
259  WriteStream = writeStream;
260  byte[] array = null;
261  if (Header != null)
262  {
263  array = Header;
264  Header = null;
265  }
266  else
267  {
268  array = new byte[0];
269  }
270  if (Async)
271  {
272  Progress.BytesSent += array.Length;
273  WriteStream.BeginWrite(array, 0, array.Length, UploadBitsWriteCallback, this);
274  }
275  else
276  {
277  WriteStream.Write(array, 0, array.Length);
278  }
279  }
280 
281  internal bool WriteBytes()
282  {
283  byte[] array = null;
284  int num = 0;
285  int num2 = 0;
286  if (Async)
287  {
288  WebClient.PostProgressChanged(AsyncOp, Progress);
289  }
290  if (FileUpload)
291  {
292  int num3 = 0;
293  if (InnerBuffer != null)
294  {
295  num3 = ReadStream.Read(InnerBuffer, 0, InnerBuffer.Length);
296  if (num3 <= 0)
297  {
298  ReadStream.Close();
299  InnerBuffer = null;
300  }
301  }
302  if (InnerBuffer != null)
303  {
304  num = num3;
305  array = InnerBuffer;
306  }
307  else
308  {
309  if (Footer == null)
310  {
311  return true;
312  }
313  num = Footer.Length;
314  array = Footer;
315  Footer = null;
316  }
317  }
318  else
319  {
320  if (InnerBuffer == null)
321  {
322  return true;
323  }
324  array = InnerBuffer;
325  if (m_ChunkSize != 0)
326  {
327  num2 = m_BufferWritePosition;
328  m_BufferWritePosition += m_ChunkSize;
329  num = m_ChunkSize;
330  if (m_BufferWritePosition >= InnerBuffer.Length)
331  {
332  num = InnerBuffer.Length - num2;
333  InnerBuffer = null;
334  }
335  }
336  else
337  {
338  num = InnerBuffer.Length;
339  InnerBuffer = null;
340  }
341  }
342  if (Async)
343  {
344  Progress.BytesSent += num;
345  WriteStream.BeginWrite(array, num2, num, UploadBitsWriteCallback, this);
346  }
347  else
348  {
349  WriteStream.Write(array, 0, num);
350  }
351  return false;
352  }
353 
354  internal void Close()
355  {
356  if (WriteStream != null)
357  {
358  WriteStream.Close();
359  }
360  if (ReadStream != null)
361  {
362  ReadStream.Close();
363  }
364  }
365  }
366 
367  private class WebClientWriteStream : Stream
368  {
369  private WebRequest m_request;
370 
371  private Stream m_stream;
372 
373  private WebClient m_WebClient;
374 
375  public override bool CanRead => m_stream.CanRead;
376 
377  public override bool CanSeek => m_stream.CanSeek;
378 
379  public override bool CanWrite => m_stream.CanWrite;
380 
381  public override bool CanTimeout => m_stream.CanTimeout;
382 
383  public override int ReadTimeout
384  {
385  get
386  {
387  return m_stream.ReadTimeout;
388  }
389  set
390  {
391  m_stream.ReadTimeout = value;
392  }
393  }
394 
395  public override int WriteTimeout
396  {
397  get
398  {
399  return m_stream.WriteTimeout;
400  }
401  set
402  {
403  m_stream.WriteTimeout = value;
404  }
405  }
406 
407  public override long Length => m_stream.Length;
408 
409  public override long Position
410  {
411  get
412  {
413  return m_stream.Position;
414  }
415  set
416  {
417  m_stream.Position = value;
418  }
419  }
420 
421  public WebClientWriteStream(Stream stream, WebRequest request, WebClient webClient)
422  {
423  m_request = request;
424  m_stream = stream;
425  m_WebClient = webClient;
426  }
427 
428  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
429  public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
430  {
431  return m_stream.BeginRead(buffer, offset, size, callback, state);
432  }
433 
434  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
435  public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
436  {
437  return m_stream.BeginWrite(buffer, offset, size, callback, state);
438  }
439 
440  protected override void Dispose(bool disposing)
441  {
442  try
443  {
444  if (disposing)
445  {
446  m_stream.Close();
447  m_WebClient.GetWebResponse(m_request).Close();
448  }
449  }
450  finally
451  {
452  base.Dispose(disposing);
453  }
454  }
455 
456  public override int EndRead(IAsyncResult result)
457  {
458  return m_stream.EndRead(result);
459  }
460 
461  public override void EndWrite(IAsyncResult result)
462  {
463  m_stream.EndWrite(result);
464  }
465 
466  public override void Flush()
467  {
468  m_stream.Flush();
469  }
470 
471  public override int Read(byte[] buffer, int offset, int count)
472  {
473  return m_stream.Read(buffer, offset, count);
474  }
475 
476  public override long Seek(long offset, SeekOrigin origin)
477  {
478  return m_stream.Seek(offset, origin);
479  }
480 
481  public override void SetLength(long value)
482  {
483  m_stream.SetLength(value);
484  }
485 
486  public override void Write(byte[] buffer, int offset, int count)
487  {
488  m_stream.Write(buffer, offset, count);
489  }
490  }
491 
492  private const int DefaultCopyBufferLength = 8192;
493 
494  private const int DefaultDownloadBufferLength = 65536;
495 
496  private const string DefaultUploadFileContentType = "application/octet-stream";
497 
498  private const string UploadFileContentType = "multipart/form-data";
499 
500  private const string UploadValuesContentType = "application/x-www-form-urlencoded";
501 
502  private Uri m_baseAddress;
503 
504  private ICredentials m_credentials;
505 
506  private WebHeaderCollection m_headers;
507 
508  private NameValueCollection m_requestParameters;
509 
510  private WebResponse m_WebResponse;
511 
512  private WebRequest m_WebRequest;
513 
514  private Encoding m_Encoding = Encoding.Default;
515 
516  private string m_Method;
517 
518  private long m_ContentLength = -1L;
519 
520  private bool m_InitWebClientAsync;
521 
522  private bool m_Cancelled;
523 
524  private ProgressData m_Progress;
525 
526  private IWebProxy m_Proxy;
527 
528  private bool m_ProxySet;
529 
530  private RequestCachePolicy m_CachePolicy;
531 
532  private int m_CallNesting;
533 
534  private AsyncOperation m_AsyncOp;
535 
536  private SendOrPostCallback openReadOperationCompleted;
537 
538  private SendOrPostCallback openWriteOperationCompleted;
539 
540  private SendOrPostCallback downloadStringOperationCompleted;
541 
542  private SendOrPostCallback downloadDataOperationCompleted;
543 
544  private SendOrPostCallback downloadFileOperationCompleted;
545 
546  private SendOrPostCallback uploadStringOperationCompleted;
547 
548  private SendOrPostCallback uploadDataOperationCompleted;
549 
550  private SendOrPostCallback uploadFileOperationCompleted;
551 
552  private SendOrPostCallback uploadValuesOperationCompleted;
553 
554  private SendOrPostCallback reportDownloadProgressChanged;
555 
556  private SendOrPostCallback reportUploadProgressChanged;
557 
561  [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
562  [EditorBrowsable(EditorBrowsableState.Never)]
563  public bool AllowReadStreamBuffering
564  {
565  get;
566  set;
567  }
568 
572  [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
573  [EditorBrowsable(EditorBrowsableState.Never)]
574  public bool AllowWriteStreamBuffering
575  {
576  get;
577  set;
578  }
579 
582  public Encoding Encoding
583  {
584  get
585  {
586  return m_Encoding;
587  }
588  set
589  {
590  if (value == null)
591  {
592  throw new ArgumentNullException("Encoding");
593  }
594  m_Encoding = value;
595  }
596  }
597 
602  public string BaseAddress
603  {
604  get
605  {
606  if (!(m_baseAddress == null))
607  {
608  return m_baseAddress.ToString();
609  }
610  return string.Empty;
611  }
612  set
613  {
614  if (value == null || value.Length == 0)
615  {
616  m_baseAddress = null;
617  }
618  else
619  {
620  try
621  {
622  m_baseAddress = new Uri(value);
623  }
624  catch (UriFormatException innerException)
625  {
626  throw new ArgumentException(SR.GetString("net_webclient_invalid_baseaddress"), "value", innerException);
627  }
628  }
629  }
630  }
631 
635  {
636  get
637  {
638  return m_credentials;
639  }
640  set
641  {
642  m_credentials = value;
643  }
644  }
645 
649  public bool UseDefaultCredentials
650  {
651  get
652  {
653  if (!(m_credentials is SystemNetworkCredential))
654  {
655  return false;
656  }
657  return true;
658  }
659  set
660  {
661  m_credentials = (value ? CredentialCache.DefaultCredentials : null);
662  }
663  }
664 
668  {
669  get
670  {
671  if (m_headers == null)
672  {
673  m_headers = new WebHeaderCollection(WebHeaderCollectionType.WebRequest);
674  }
675  return m_headers;
676  }
677  set
678  {
679  m_headers = value;
680  }
681  }
682 
686  {
687  get
688  {
689  if (m_requestParameters == null)
690  {
691  m_requestParameters = new NameValueCollection();
692  }
693  return m_requestParameters;
694  }
695  set
696  {
697  m_requestParameters = value;
698  }
699  }
700 
704  {
705  get
706  {
707  if (m_WebResponse != null)
708  {
709  return m_WebResponse.Headers;
710  }
711  return null;
712  }
713  }
714 
719  public IWebProxy Proxy
720  {
721  get
722  {
723  ExceptionHelper.WebPermissionUnrestricted.Demand();
724  if (!m_ProxySet)
725  {
726  return WebRequest.InternalDefaultWebProxy;
727  }
728  return m_Proxy;
729  }
730  set
731  {
732  ExceptionHelper.WebPermissionUnrestricted.Demand();
733  m_Proxy = value;
734  m_ProxySet = true;
735  }
736  }
737 
741  {
742  get
743  {
744  return m_CachePolicy;
745  }
746  set
747  {
748  m_CachePolicy = value;
749  }
750  }
751 
755  public bool IsBusy => m_AsyncOp != null;
756 
758  [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
759  [EditorBrowsable(EditorBrowsableState.Never)]
761  {
762  add
763  {
764  }
765  remove
766  {
767  }
768  }
769 
772 
775 
778 
781 
784 
787 
790 
793 
796 
799 
802 
804  public WebClient()
805  {
806  if (GetType() == typeof(WebClient))
807  {
808  GC.SuppressFinalize(this);
809  }
810  }
811 
812  private void InitWebClientAsync()
813  {
814  if (!m_InitWebClientAsync)
815  {
816  openReadOperationCompleted = OpenReadOperationCompleted;
817  openWriteOperationCompleted = OpenWriteOperationCompleted;
818  downloadStringOperationCompleted = DownloadStringOperationCompleted;
819  downloadDataOperationCompleted = DownloadDataOperationCompleted;
820  downloadFileOperationCompleted = DownloadFileOperationCompleted;
821  uploadStringOperationCompleted = UploadStringOperationCompleted;
822  uploadDataOperationCompleted = UploadDataOperationCompleted;
823  uploadFileOperationCompleted = UploadFileOperationCompleted;
824  uploadValuesOperationCompleted = UploadValuesOperationCompleted;
825  reportDownloadProgressChanged = ReportDownloadProgressChanged;
826  reportUploadProgressChanged = ReportUploadProgressChanged;
827  m_Progress = new ProgressData();
828  m_InitWebClientAsync = true;
829  }
830  }
831 
832  private void ClearWebClientState()
833  {
834  if (AnotherCallInProgress(Interlocked.Increment(ref m_CallNesting)))
835  {
836  CompleteWebClientState();
837  throw new NotSupportedException(SR.GetString("net_webclient_no_concurrent_io_allowed"));
838  }
839  m_ContentLength = -1L;
840  m_WebResponse = null;
841  m_WebRequest = null;
842  m_Method = null;
843  m_Cancelled = false;
844  if (m_Progress != null)
845  {
846  m_Progress.Reset();
847  }
848  }
849 
850  private void CompleteWebClientState()
851  {
852  Interlocked.Decrement(ref m_CallNesting);
853  }
854 
857  [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
858  [EditorBrowsable(EditorBrowsableState.Never)]
860  {
861  }
862 
866  protected virtual WebRequest GetWebRequest(Uri address)
867  {
868  WebRequest webRequest = WebRequest.Create(address);
869  CopyHeadersTo(webRequest);
870  if (Credentials != null)
871  {
872  webRequest.Credentials = Credentials;
873  }
874  if (m_Method != null)
875  {
876  webRequest.Method = m_Method;
877  }
878  if (m_ContentLength != -1)
879  {
880  webRequest.ContentLength = m_ContentLength;
881  }
882  if (m_ProxySet)
883  {
884  webRequest.Proxy = m_Proxy;
885  }
886  if (m_CachePolicy != null)
887  {
888  webRequest.CachePolicy = m_CachePolicy;
889  }
890  return webRequest;
891  }
892 
896  protected virtual WebResponse GetWebResponse(WebRequest request)
897  {
898  return m_WebResponse = request.GetResponse();
899  }
900 
905  protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
906  {
907  return m_WebResponse = request.EndGetResponse(result);
908  }
909 
916  public byte[] DownloadData(string address)
917  {
918  if (address == null)
919  {
920  throw new ArgumentNullException("address");
921  }
922  return DownloadData(GetUri(address));
923  }
924 
929  public byte[] DownloadData(Uri address)
930  {
931  if (Logging.On)
932  {
933  Logging.Enter(Logging.Web, this, "DownloadData", address);
934  }
935  if (address == null)
936  {
937  throw new ArgumentNullException("address");
938  }
939  ClearWebClientState();
940  byte[] array = null;
941  try
942  {
943  array = DownloadDataInternal(address, out WebRequest _);
944  if (Logging.On)
945  {
946  Logging.Exit(Logging.Web, this, "DownloadData", array);
947  }
948  return array;
949  }
950  finally
951  {
952  CompleteWebClientState();
953  }
954  }
955 
956  private byte[] DownloadDataInternal(Uri address, out WebRequest request)
957  {
958  if (Logging.On)
959  {
960  Logging.Enter(Logging.Web, this, "DownloadData", address);
961  }
962  request = null;
963  try
964  {
965  request = (m_WebRequest = GetWebRequest(GetUri(address)));
966  return DownloadBits(request, null, null, null);
967  }
968  catch (Exception ex)
969  {
970  Exception ex2 = ex;
971  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
972  {
973  throw;
974  }
975  if (!(ex2 is WebException) && !(ex2 is SecurityException))
976  {
977  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
978  }
979  AbortRequest(request);
980  throw ex2;
981  }
982  }
983 
991  public void DownloadFile(string address, string fileName)
992  {
993  if (address == null)
994  {
995  throw new ArgumentNullException("address");
996  }
997  DownloadFile(GetUri(address), fileName);
998  }
999 
1007  public void DownloadFile(Uri address, string fileName)
1008  {
1009  if (Logging.On)
1010  {
1011  Logging.Enter(Logging.Web, this, "DownloadFile", address + ", " + fileName);
1012  }
1013  if (address == null)
1014  {
1015  throw new ArgumentNullException("address");
1016  }
1017  if (fileName == null)
1018  {
1019  throw new ArgumentNullException("fileName");
1020  }
1021  WebRequest request = null;
1022  FileStream fileStream = null;
1023  bool flag = false;
1024  ClearWebClientState();
1025  try
1026  {
1027  fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
1028  request = (m_WebRequest = GetWebRequest(GetUri(address)));
1029  DownloadBits(request, fileStream, null, null);
1030  flag = true;
1031  }
1032  catch (Exception ex)
1033  {
1034  Exception ex2 = ex;
1035  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1036  {
1037  throw;
1038  }
1039  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1040  {
1041  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1042  }
1043  AbortRequest(request);
1044  throw ex2;
1045  }
1046  finally
1047  {
1048  if (fileStream != null)
1049  {
1050  fileStream.Close();
1051  if (!flag)
1052  {
1053  File.Delete(fileName);
1054  }
1055  fileStream = null;
1056  }
1057  CompleteWebClientState();
1058  }
1059  if (Logging.On)
1060  {
1061  Logging.Exit(Logging.Web, this, "DownloadFile", "");
1062  }
1063  }
1064 
1070  public Stream OpenRead(string address)
1071  {
1072  if (address == null)
1073  {
1074  throw new ArgumentNullException("address");
1075  }
1076  return OpenRead(GetUri(address));
1077  }
1078 
1084  public Stream OpenRead(Uri address)
1085  {
1086  if (Logging.On)
1087  {
1088  Logging.Enter(Logging.Web, this, "OpenRead", address);
1089  }
1090  if (address == null)
1091  {
1092  throw new ArgumentNullException("address");
1093  }
1094  WebRequest request = null;
1095  ClearWebClientState();
1096  try
1097  {
1098  request = (m_WebRequest = GetWebRequest(GetUri(address)));
1099  Stream responseStream = (m_WebResponse = GetWebResponse(request)).GetResponseStream();
1100  if (Logging.On)
1101  {
1102  Logging.Exit(Logging.Web, this, "OpenRead", responseStream);
1103  }
1104  return responseStream;
1105  }
1106  catch (Exception ex)
1107  {
1108  Exception ex2 = ex;
1109  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1110  {
1111  throw;
1112  }
1113  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1114  {
1115  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1116  }
1117  AbortRequest(request);
1118  throw ex2;
1119  }
1120  finally
1121  {
1122  CompleteWebClientState();
1123  }
1124  }
1125 
1131  public Stream OpenWrite(string address)
1132  {
1133  if (address == null)
1134  {
1135  throw new ArgumentNullException("address");
1136  }
1137  return OpenWrite(GetUri(address), null);
1138  }
1139 
1145  public Stream OpenWrite(Uri address)
1146  {
1147  return OpenWrite(address, null);
1148  }
1149 
1156  public Stream OpenWrite(string address, string method)
1157  {
1158  if (address == null)
1159  {
1160  throw new ArgumentNullException("address");
1161  }
1162  return OpenWrite(GetUri(address), method);
1163  }
1164 
1171  public Stream OpenWrite(Uri address, string method)
1172  {
1173  if (Logging.On)
1174  {
1175  Logging.Enter(Logging.Web, this, "OpenWrite", address + ", " + method);
1176  }
1177  if (address == null)
1178  {
1179  throw new ArgumentNullException("address");
1180  }
1181  if (method == null)
1182  {
1183  method = MapToDefaultMethod(address);
1184  }
1185  WebRequest webRequest = null;
1186  ClearWebClientState();
1187  try
1188  {
1189  m_Method = method;
1190  webRequest = (m_WebRequest = GetWebRequest(GetUri(address)));
1191  WebClientWriteStream webClientWriteStream = new WebClientWriteStream(webRequest.GetRequestStream(), webRequest, this);
1192  if (Logging.On)
1193  {
1194  Logging.Exit(Logging.Web, this, "OpenWrite", webClientWriteStream);
1195  }
1196  return webClientWriteStream;
1197  }
1198  catch (Exception ex)
1199  {
1200  Exception ex2 = ex;
1201  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1202  {
1203  throw;
1204  }
1205  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1206  {
1207  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1208  }
1209  AbortRequest(webRequest);
1210  throw ex2;
1211  }
1212  finally
1213  {
1214  CompleteWebClientState();
1215  }
1216  }
1217 
1225  public byte[] UploadData(string address, byte[] data)
1226  {
1227  if (address == null)
1228  {
1229  throw new ArgumentNullException("address");
1230  }
1231  return UploadData(GetUri(address), null, data);
1232  }
1233 
1241  public byte[] UploadData(Uri address, byte[] data)
1242  {
1243  return UploadData(address, null, data);
1244  }
1245 
1254  public byte[] UploadData(string address, string method, byte[] data)
1255  {
1256  if (address == null)
1257  {
1258  throw new ArgumentNullException("address");
1259  }
1260  return UploadData(GetUri(address), method, data);
1261  }
1262 
1271  public byte[] UploadData(Uri address, string method, byte[] data)
1272  {
1273  if (Logging.On)
1274  {
1275  Logging.Enter(Logging.Web, this, "UploadData", address + ", " + method);
1276  }
1277  if (address == null)
1278  {
1279  throw new ArgumentNullException("address");
1280  }
1281  if (data == null)
1282  {
1283  throw new ArgumentNullException("data");
1284  }
1285  if (method == null)
1286  {
1287  method = MapToDefaultMethod(address);
1288  }
1289  ClearWebClientState();
1290  try
1291  {
1292  WebRequest request;
1293  byte[] array = UploadDataInternal(address, method, data, out request);
1294  if (Logging.On)
1295  {
1296  Logging.Exit(Logging.Web, this, "UploadData", array);
1297  }
1298  return array;
1299  }
1300  finally
1301  {
1302  CompleteWebClientState();
1303  }
1304  }
1305 
1306  private byte[] UploadDataInternal(Uri address, string method, byte[] data, out WebRequest request)
1307  {
1308  request = null;
1309  try
1310  {
1311  m_Method = method;
1312  m_ContentLength = data.Length;
1313  request = (m_WebRequest = GetWebRequest(GetUri(address)));
1314  UploadBits(request, null, data, 0, null, null, null, null, null);
1315  return DownloadBits(request, null, null, null);
1316  }
1317  catch (Exception ex)
1318  {
1319  Exception ex2 = ex;
1320  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1321  {
1322  throw;
1323  }
1324  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1325  {
1326  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1327  }
1328  AbortRequest(request);
1329  throw ex2;
1330  }
1331  }
1332 
1333  private void OpenFileInternal(bool needsHeaderAndBoundary, string fileName, ref FileStream fs, ref byte[] buffer, ref byte[] formHeaderBytes, ref byte[] boundaryBytes)
1334  {
1335  fileName = Path.GetFullPath(fileName);
1336  if (m_headers == null)
1337  {
1338  m_headers = new WebHeaderCollection(WebHeaderCollectionType.WebRequest);
1339  }
1340  string text = m_headers["Content-Type"];
1341  if (text != null)
1342  {
1343  if (text.ToLower(CultureInfo.InvariantCulture).StartsWith("multipart/"))
1344  {
1345  throw new WebException(SR.GetString("net_webclient_Multipart"));
1346  }
1347  }
1348  else
1349  {
1350  text = "application/octet-stream";
1351  }
1352  fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
1353  int num = 8192;
1354  m_ContentLength = -1L;
1355  if (m_Method.ToUpper(CultureInfo.InvariantCulture) == "POST")
1356  {
1357  if (needsHeaderAndBoundary)
1358  {
1359  string text2 = "---------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
1360  m_headers["Content-Type"] = "multipart/form-data; boundary=" + text2;
1361  string s = "--" + text2 + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + Path.GetFileName(fileName) + "\"\r\nContent-Type: " + text + "\r\n\r\n";
1362  formHeaderBytes = Encoding.UTF8.GetBytes(s);
1363  boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + text2 + "--\r\n");
1364  }
1365  else
1366  {
1367  formHeaderBytes = new byte[0];
1368  boundaryBytes = new byte[0];
1369  }
1370  if (fs.CanSeek)
1371  {
1372  m_ContentLength = fs.Length + formHeaderBytes.Length + boundaryBytes.Length;
1373  num = (int)Math.Min(8192L, fs.Length);
1374  }
1375  }
1376  else
1377  {
1378  m_headers["Content-Type"] = text;
1379  formHeaderBytes = null;
1380  boundaryBytes = null;
1381  if (fs.CanSeek)
1382  {
1383  m_ContentLength = fs.Length;
1384  num = (int)Math.Min(8192L, fs.Length);
1385  }
1386  }
1387  buffer = new byte[num];
1388  }
1389 
1397  public byte[] UploadFile(string address, string fileName)
1398  {
1399  if (address == null)
1400  {
1401  throw new ArgumentNullException("address");
1402  }
1403  return UploadFile(GetUri(address), fileName);
1404  }
1405 
1413  public byte[] UploadFile(Uri address, string fileName)
1414  {
1415  return UploadFile(address, null, fileName);
1416  }
1417 
1426  public byte[] UploadFile(string address, string method, string fileName)
1427  {
1428  return UploadFile(GetUri(address), method, fileName);
1429  }
1430 
1439  public byte[] UploadFile(Uri address, string method, string fileName)
1440  {
1441  if (Logging.On)
1442  {
1443  Logging.Enter(Logging.Web, this, "UploadFile", address + ", " + method);
1444  }
1445  if (address == null)
1446  {
1447  throw new ArgumentNullException("address");
1448  }
1449  if (fileName == null)
1450  {
1451  throw new ArgumentNullException("fileName");
1452  }
1453  if (method == null)
1454  {
1455  method = MapToDefaultMethod(address);
1456  }
1457  FileStream fs = null;
1458  WebRequest request = null;
1459  ClearWebClientState();
1460  try
1461  {
1462  m_Method = method;
1463  byte[] formHeaderBytes = null;
1464  byte[] boundaryBytes = null;
1465  byte[] buffer = null;
1466  Uri uri = GetUri(address);
1467  bool needsHeaderAndBoundary = uri.Scheme != Uri.UriSchemeFile;
1468  OpenFileInternal(needsHeaderAndBoundary, fileName, ref fs, ref buffer, ref formHeaderBytes, ref boundaryBytes);
1469  request = (m_WebRequest = GetWebRequest(uri));
1470  UploadBits(request, fs, buffer, 0, formHeaderBytes, boundaryBytes, null, null, null);
1471  byte[] array = DownloadBits(request, null, null, null);
1472  if (Logging.On)
1473  {
1474  Logging.Exit(Logging.Web, this, "UploadFile", array);
1475  }
1476  return array;
1477  }
1478  catch (Exception ex)
1479  {
1480  Exception ex2 = ex;
1481  if (fs != null)
1482  {
1483  fs.Close();
1484  fs = null;
1485  }
1486  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1487  {
1488  throw;
1489  }
1490  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1491  {
1492  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1493  }
1494  AbortRequest(request);
1495  throw ex2;
1496  }
1497  finally
1498  {
1499  CompleteWebClientState();
1500  }
1501  }
1502 
1503  private byte[] UploadValuesInternal(NameValueCollection data)
1504  {
1505  if (m_headers == null)
1506  {
1507  m_headers = new WebHeaderCollection(WebHeaderCollectionType.WebRequest);
1508  }
1509  string text = m_headers["Content-Type"];
1510  if (text != null && string.Compare(text, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != 0)
1511  {
1512  throw new WebException(SR.GetString("net_webclient_ContentType"));
1513  }
1514  m_headers["Content-Type"] = "application/x-www-form-urlencoded";
1515  string value = string.Empty;
1516  StringBuilder stringBuilder = new StringBuilder();
1517  string[] allKeys = data.AllKeys;
1518  foreach (string text2 in allKeys)
1519  {
1520  stringBuilder.Append(value);
1521  stringBuilder.Append(UrlEncode(text2));
1522  stringBuilder.Append("=");
1523  stringBuilder.Append(UrlEncode(data[text2]));
1524  value = "&";
1525  }
1526  byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString());
1527  m_ContentLength = bytes.Length;
1528  return bytes;
1529  }
1530 
1538  public byte[] UploadValues(string address, NameValueCollection data)
1539  {
1540  if (address == null)
1541  {
1542  throw new ArgumentNullException("address");
1543  }
1544  return UploadValues(GetUri(address), null, data);
1545  }
1546 
1554  public byte[] UploadValues(Uri address, NameValueCollection data)
1555  {
1556  return UploadValues(address, null, data);
1557  }
1558 
1567  public byte[] UploadValues(string address, string method, NameValueCollection data)
1568  {
1569  if (address == null)
1570  {
1571  throw new ArgumentNullException("address");
1572  }
1573  return UploadValues(GetUri(address), method, data);
1574  }
1575 
1584  public byte[] UploadValues(Uri address, string method, NameValueCollection data)
1585  {
1586  if (Logging.On)
1587  {
1588  Logging.Enter(Logging.Web, this, "UploadValues", address + ", " + method);
1589  }
1590  if (address == null)
1591  {
1592  throw new ArgumentNullException("address");
1593  }
1594  if (data == null)
1595  {
1596  throw new ArgumentNullException("data");
1597  }
1598  if (method == null)
1599  {
1600  method = MapToDefaultMethod(address);
1601  }
1602  WebRequest request = null;
1603  ClearWebClientState();
1604  try
1605  {
1606  byte[] buffer = UploadValuesInternal(data);
1607  m_Method = method;
1608  request = (m_WebRequest = GetWebRequest(GetUri(address)));
1609  UploadBits(request, null, buffer, 0, null, null, null, null, null);
1610  byte[] result = DownloadBits(request, null, null, null);
1611  if (Logging.On)
1612  {
1613  Logging.Exit(Logging.Web, this, "UploadValues", address + ", " + method);
1614  }
1615  return result;
1616  }
1617  catch (Exception ex)
1618  {
1619  Exception ex2 = ex;
1620  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1621  {
1622  throw;
1623  }
1624  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1625  {
1626  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
1627  }
1628  AbortRequest(request);
1629  throw ex2;
1630  }
1631  finally
1632  {
1633  CompleteWebClientState();
1634  }
1635  }
1636 
1643  public string UploadString(string address, string data)
1644  {
1645  if (address == null)
1646  {
1647  throw new ArgumentNullException("address");
1648  }
1649  return UploadString(GetUri(address), null, data);
1650  }
1651 
1658  public string UploadString(Uri address, string data)
1659  {
1660  return UploadString(address, null, data);
1661  }
1662 
1671  public string UploadString(string address, string method, string data)
1672  {
1673  if (address == null)
1674  {
1675  throw new ArgumentNullException("address");
1676  }
1677  return UploadString(GetUri(address), method, data);
1678  }
1679 
1688  public string UploadString(Uri address, string method, string data)
1689  {
1690  if (Logging.On)
1691  {
1692  Logging.Enter(Logging.Web, this, "UploadString", address + ", " + method);
1693  }
1694  if (address == null)
1695  {
1696  throw new ArgumentNullException("address");
1697  }
1698  if (data == null)
1699  {
1700  throw new ArgumentNullException("data");
1701  }
1702  if (method == null)
1703  {
1704  method = MapToDefaultMethod(address);
1705  }
1706  ClearWebClientState();
1707  try
1708  {
1709  byte[] bytes = Encoding.GetBytes(data);
1710  WebRequest request;
1711  byte[] data2 = UploadDataInternal(address, method, bytes, out request);
1712  string stringUsingEncoding = GetStringUsingEncoding(request, data2);
1713  if (Logging.On)
1714  {
1715  Logging.Exit(Logging.Web, this, "UploadString", stringUsingEncoding);
1716  }
1717  return stringUsingEncoding;
1718  }
1719  finally
1720  {
1721  CompleteWebClientState();
1722  }
1723  }
1724 
1731  public string DownloadString(string address)
1732  {
1733  if (address == null)
1734  {
1735  throw new ArgumentNullException("address");
1736  }
1737  return DownloadString(GetUri(address));
1738  }
1739 
1746  public string DownloadString(Uri address)
1747  {
1748  if (Logging.On)
1749  {
1750  Logging.Enter(Logging.Web, this, "DownloadString", address);
1751  }
1752  if (address == null)
1753  {
1754  throw new ArgumentNullException("address");
1755  }
1756  ClearWebClientState();
1757  try
1758  {
1759  WebRequest request;
1760  byte[] data = DownloadDataInternal(address, out request);
1761  string stringUsingEncoding = GetStringUsingEncoding(request, data);
1762  if (Logging.On)
1763  {
1764  Logging.Exit(Logging.Web, this, "DownloadString", stringUsingEncoding);
1765  }
1766  return stringUsingEncoding;
1767  }
1768  finally
1769  {
1770  CompleteWebClientState();
1771  }
1772  }
1773 
1774  private static void AbortRequest(WebRequest request)
1775  {
1776  try
1777  {
1778  request?.Abort();
1779  }
1780  catch (Exception ex)
1781  {
1783  {
1784  throw;
1785  }
1786  }
1787  }
1788 
1789  private void CopyHeadersTo(WebRequest request)
1790  {
1791  if (m_headers != null && request is HttpWebRequest)
1792  {
1793  string text = m_headers["Accept"];
1794  string text2 = m_headers["Connection"];
1795  string text3 = m_headers["Content-Type"];
1796  string text4 = m_headers["Expect"];
1797  string text5 = m_headers["Referer"];
1798  string text6 = m_headers["User-Agent"];
1799  string text7 = m_headers["Host"];
1800  m_headers.RemoveInternal("Accept");
1801  m_headers.RemoveInternal("Connection");
1802  m_headers.RemoveInternal("Content-Type");
1803  m_headers.RemoveInternal("Expect");
1804  m_headers.RemoveInternal("Referer");
1805  m_headers.RemoveInternal("User-Agent");
1806  m_headers.RemoveInternal("Host");
1807  request.Headers = m_headers;
1808  if (text != null && text.Length > 0)
1809  {
1810  ((HttpWebRequest)request).Accept = text;
1811  }
1812  if (text2 != null && text2.Length > 0)
1813  {
1814  ((HttpWebRequest)request).Connection = text2;
1815  }
1816  if (text3 != null && text3.Length > 0)
1817  {
1818  ((HttpWebRequest)request).ContentType = text3;
1819  }
1820  if (text4 != null && text4.Length > 0)
1821  {
1822  ((HttpWebRequest)request).Expect = text4;
1823  }
1824  if (text5 != null && text5.Length > 0)
1825  {
1826  ((HttpWebRequest)request).Referer = text5;
1827  }
1828  if (text6 != null && text6.Length > 0)
1829  {
1830  ((HttpWebRequest)request).UserAgent = text6;
1831  }
1832  if (!string.IsNullOrEmpty(text7))
1833  {
1834  ((HttpWebRequest)request).Host = text7;
1835  }
1836  }
1837  }
1838 
1839  private Uri GetUri(string path)
1840  {
1841  Uri result;
1842  if (m_baseAddress != null)
1843  {
1844  if (!Uri.TryCreate(m_baseAddress, path, out result))
1845  {
1846  return new Uri(Path.GetFullPath(path));
1847  }
1848  }
1849  else if (!Uri.TryCreate(path, UriKind.Absolute, out result))
1850  {
1851  return new Uri(Path.GetFullPath(path));
1852  }
1853  return GetUri(result);
1854  }
1855 
1856  private Uri GetUri(Uri address)
1857  {
1858  if (address == null)
1859  {
1860  throw new ArgumentNullException("address");
1861  }
1862  Uri result = address;
1863  if (!address.IsAbsoluteUri && m_baseAddress != null && !Uri.TryCreate(m_baseAddress, address, out result))
1864  {
1865  return address;
1866  }
1867  if ((result.Query == null || result.Query == string.Empty) && m_requestParameters != null)
1868  {
1869  StringBuilder stringBuilder = new StringBuilder();
1870  string str = string.Empty;
1871  for (int i = 0; i < m_requestParameters.Count; i++)
1872  {
1873  stringBuilder.Append(str + m_requestParameters.AllKeys[i] + "=" + m_requestParameters[i]);
1874  str = "&";
1875  }
1876  UriBuilder uriBuilder = new UriBuilder(result);
1877  uriBuilder.Query = stringBuilder.ToString();
1878  result = uriBuilder.Uri;
1879  }
1880  return result;
1881  }
1882 
1883  private static void DownloadBitsResponseCallback(IAsyncResult result)
1884  {
1885  DownloadBitsState downloadBitsState = (DownloadBitsState)result.AsyncState;
1886  WebRequest request = downloadBitsState.Request;
1887  Exception ex = null;
1888  try
1889  {
1890  WebResponse webResponse = downloadBitsState.WebClient.GetWebResponse(request, result);
1891  downloadBitsState.WebClient.m_WebResponse = webResponse;
1892  downloadBitsState.SetResponse(webResponse);
1893  }
1894  catch (Exception ex2)
1895  {
1896  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1897  {
1898  throw;
1899  }
1900  ex = ex2;
1901  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1902  {
1903  ex = new WebException(SR.GetString("net_webclient"), ex2);
1904  }
1905  AbortRequest(request);
1906  if (downloadBitsState != null && downloadBitsState.WriteStream != null)
1907  {
1908  downloadBitsState.WriteStream.Close();
1909  }
1910  }
1911  finally
1912  {
1913  if (ex != null)
1914  {
1915  downloadBitsState.CompletionDelegate(null, ex, downloadBitsState.AsyncOp);
1916  }
1917  }
1918  }
1919 
1920  private static void DownloadBitsReadCallback(IAsyncResult result)
1921  {
1922  DownloadBitsState state = (DownloadBitsState)result.AsyncState;
1923  DownloadBitsReadCallbackState(state, result);
1924  }
1925 
1926  private static void DownloadBitsReadCallbackState(DownloadBitsState state, IAsyncResult result)
1927  {
1928  Stream readStream = state.ReadStream;
1929  Exception ex = null;
1930  bool flag = false;
1931  try
1932  {
1933  int bytesRetrieved = 0;
1934  if (readStream != null && readStream != Stream.Null)
1935  {
1936  bytesRetrieved = readStream.EndRead(result);
1937  }
1938  flag = state.RetrieveBytes(ref bytesRetrieved);
1939  }
1940  catch (Exception ex2)
1941  {
1942  flag = true;
1943  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
1944  {
1945  throw;
1946  }
1947  ex = ex2;
1948  state.InnerBuffer = null;
1949  if (!(ex2 is WebException) && !(ex2 is SecurityException))
1950  {
1951  ex = new WebException(SR.GetString("net_webclient"), ex2);
1952  }
1953  AbortRequest(state.Request);
1954  if (state != null && state.WriteStream != null)
1955  {
1956  state.WriteStream.Close();
1957  }
1958  }
1959  finally
1960  {
1961  if (flag)
1962  {
1963  if (ex == null)
1964  {
1965  state.Close();
1966  }
1967  state.CompletionDelegate(state.InnerBuffer, ex, state.AsyncOp);
1968  }
1969  }
1970  }
1971 
1972  private byte[] DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp)
1973  {
1974  WebResponse webResponse = null;
1975  DownloadBitsState downloadBitsState = new DownloadBitsState(request, writeStream, completionDelegate, asyncOp, m_Progress, this);
1976  if (downloadBitsState.Async)
1977  {
1978  request.BeginGetResponse(DownloadBitsResponseCallback, downloadBitsState);
1979  return null;
1980  }
1981  int bytesRetrieved = downloadBitsState.SetResponse(m_WebResponse = GetWebResponse(request));
1982  while (!downloadBitsState.RetrieveBytes(ref bytesRetrieved))
1983  {
1984  }
1985  downloadBitsState.Close();
1986  return downloadBitsState.InnerBuffer;
1987  }
1988 
1989  private static void UploadBitsRequestCallback(IAsyncResult result)
1990  {
1991  UploadBitsState uploadBitsState = (UploadBitsState)result.AsyncState;
1992  WebRequest request = uploadBitsState.Request;
1993  Exception ex = null;
1994  try
1995  {
1996  Stream requestStream = request.EndGetRequestStream(result);
1997  uploadBitsState.SetRequestStream(requestStream);
1998  }
1999  catch (Exception ex2)
2000  {
2001  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2002  {
2003  throw;
2004  }
2005  ex = ex2;
2006  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2007  {
2008  ex = new WebException(SR.GetString("net_webclient"), ex2);
2009  }
2010  AbortRequest(request);
2011  if (uploadBitsState != null && uploadBitsState.ReadStream != null)
2012  {
2013  uploadBitsState.ReadStream.Close();
2014  }
2015  }
2016  finally
2017  {
2018  if (ex != null)
2019  {
2020  uploadBitsState.UploadCompletionDelegate(null, ex, uploadBitsState);
2021  }
2022  }
2023  }
2024 
2025  private static void UploadBitsWriteCallback(IAsyncResult result)
2026  {
2027  UploadBitsState uploadBitsState = (UploadBitsState)result.AsyncState;
2028  Stream writeStream = uploadBitsState.WriteStream;
2029  Exception ex = null;
2030  bool flag = false;
2031  try
2032  {
2033  writeStream.EndWrite(result);
2034  flag = uploadBitsState.WriteBytes();
2035  }
2036  catch (Exception ex2)
2037  {
2038  flag = true;
2039  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2040  {
2041  throw;
2042  }
2043  ex = ex2;
2044  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2045  {
2046  ex = new WebException(SR.GetString("net_webclient"), ex2);
2047  }
2048  AbortRequest(uploadBitsState.Request);
2049  if (uploadBitsState != null && uploadBitsState.ReadStream != null)
2050  {
2051  uploadBitsState.ReadStream.Close();
2052  }
2053  }
2054  finally
2055  {
2056  if (flag)
2057  {
2058  if (ex == null)
2059  {
2060  uploadBitsState.Close();
2061  }
2062  uploadBitsState.UploadCompletionDelegate(null, ex, uploadBitsState);
2063  }
2064  }
2065  }
2066 
2067  private void UploadBits(WebRequest request, Stream readStream, byte[] buffer, int chunkSize, byte[] header, byte[] footer, CompletionDelegate uploadCompletionDelegate, CompletionDelegate downloadCompletionDelegate, AsyncOperation asyncOp)
2068  {
2069  if (request.RequestUri.Scheme == Uri.UriSchemeFile)
2070  {
2071  header = (footer = null);
2072  }
2073  UploadBitsState uploadBitsState = new UploadBitsState(request, readStream, buffer, chunkSize, header, footer, uploadCompletionDelegate, downloadCompletionDelegate, asyncOp, m_Progress, this);
2074  if (uploadBitsState.Async)
2075  {
2076  request.BeginGetRequestStream(UploadBitsRequestCallback, uploadBitsState);
2077  return;
2078  }
2079  Stream requestStream = request.GetRequestStream();
2080  uploadBitsState.SetRequestStream(requestStream);
2081  while (!uploadBitsState.WriteBytes())
2082  {
2083  }
2084  uploadBitsState.Close();
2085  }
2086 
2087  private bool ByteArrayHasPrefix(byte[] prefix, byte[] byteArray)
2088  {
2089  if (prefix == null || byteArray == null || prefix.Length > byteArray.Length)
2090  {
2091  return false;
2092  }
2093  for (int i = 0; i < prefix.Length; i++)
2094  {
2095  if (prefix[i] != byteArray[i])
2096  {
2097  return false;
2098  }
2099  }
2100  return true;
2101  }
2102 
2103  private string GetStringUsingEncoding(WebRequest request, byte[] data)
2104  {
2105  Encoding encoding = null;
2106  int num = -1;
2107  string text;
2108  try
2109  {
2110  text = request.ContentType;
2111  }
2112  catch (NotImplementedException)
2113  {
2114  text = null;
2115  }
2116  catch (NotSupportedException)
2117  {
2118  text = null;
2119  }
2120  if (text != null)
2121  {
2122  text = text.ToLower(CultureInfo.InvariantCulture);
2123  string[] array = text.Split(';', '=', ' ');
2124  bool flag = false;
2125  string[] array2 = array;
2126  foreach (string text2 in array2)
2127  {
2128  if (text2 == "charset")
2129  {
2130  flag = true;
2131  }
2132  else if (flag)
2133  {
2134  try
2135  {
2136  encoding = Encoding.GetEncoding(text2);
2137  }
2138  catch (ArgumentException)
2139  {
2140  goto IL_0082;
2141  }
2142  }
2143  }
2144  }
2145  goto IL_0082;
2146  IL_0082:
2147  if (encoding == null)
2148  {
2149  Encoding[] array3 = new Encoding[4]
2150  {
2151  Encoding.UTF8,
2152  Encoding.UTF32,
2153  Encoding.Unicode,
2155  };
2156  for (int j = 0; j < array3.Length; j++)
2157  {
2158  byte[] preamble = array3[j].GetPreamble();
2159  if (ByteArrayHasPrefix(preamble, data))
2160  {
2161  encoding = array3[j];
2162  num = preamble.Length;
2163  break;
2164  }
2165  }
2166  }
2167  if (encoding == null)
2168  {
2169  encoding = Encoding;
2170  }
2171  if (num == -1)
2172  {
2173  byte[] preamble2 = encoding.GetPreamble();
2174  num = (ByteArrayHasPrefix(preamble2, data) ? preamble2.Length : 0);
2175  }
2176  return encoding.GetString(data, num, data.Length - num);
2177  }
2178 
2179  private string MapToDefaultMethod(Uri address)
2180  {
2181  Uri uri = (address.IsAbsoluteUri || !(m_baseAddress != null)) ? address : new Uri(m_baseAddress, address);
2182  if (uri.Scheme.ToLower(CultureInfo.InvariantCulture) == "ftp")
2183  {
2184  return "STOR";
2185  }
2186  return "POST";
2187  }
2188 
2189  private static string UrlEncode(string str)
2190  {
2191  if (str == null)
2192  {
2193  return null;
2194  }
2195  return UrlEncode(str, Encoding.UTF8);
2196  }
2197 
2198  private static string UrlEncode(string str, Encoding e)
2199  {
2200  if (str == null)
2201  {
2202  return null;
2203  }
2204  return Encoding.ASCII.GetString(UrlEncodeToBytes(str, e));
2205  }
2206 
2207  private static byte[] UrlEncodeToBytes(string str, Encoding e)
2208  {
2209  if (str == null)
2210  {
2211  return null;
2212  }
2213  byte[] bytes = e.GetBytes(str);
2214  return UrlEncodeBytesToBytesInternal(bytes, 0, bytes.Length, alwaysCreateReturnValue: false);
2215  }
2216 
2217  private static byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
2218  {
2219  int num = 0;
2220  int num2 = 0;
2221  for (int i = 0; i < count; i++)
2222  {
2223  char c = (char)bytes[offset + i];
2224  if (c == ' ')
2225  {
2226  num++;
2227  }
2228  else if (!IsSafe(c))
2229  {
2230  num2++;
2231  }
2232  }
2233  if (!alwaysCreateReturnValue && num == 0 && num2 == 0)
2234  {
2235  return bytes;
2236  }
2237  byte[] array = new byte[count + num2 * 2];
2238  int num3 = 0;
2239  for (int j = 0; j < count; j++)
2240  {
2241  byte b = bytes[offset + j];
2242  char c2 = (char)b;
2243  if (IsSafe(c2))
2244  {
2245  array[num3++] = b;
2246  continue;
2247  }
2248  if (c2 == ' ')
2249  {
2250  array[num3++] = 43;
2251  continue;
2252  }
2253  array[num3++] = 37;
2254  array[num3++] = (byte)IntToHex((b >> 4) & 0xF);
2255  array[num3++] = (byte)IntToHex(b & 0xF);
2256  }
2257  return array;
2258  }
2259 
2260  private static char IntToHex(int n)
2261  {
2262  if (n <= 9)
2263  {
2264  return (char)(n + 48);
2265  }
2266  return (char)(n - 10 + 97);
2267  }
2268 
2269  private static bool IsSafe(char ch)
2270  {
2271  if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
2272  {
2273  return true;
2274  }
2275  switch (ch)
2276  {
2277  case '!':
2278  case '\'':
2279  case '(':
2280  case ')':
2281  case '*':
2282  case '-':
2283  case '.':
2284  case '_':
2285  return true;
2286  default:
2287  return false;
2288  }
2289  }
2290 
2291  private void InvokeOperationCompleted(AsyncOperation asyncOp, SendOrPostCallback callback, AsyncCompletedEventArgs eventArgs)
2292  {
2293  if (Interlocked.CompareExchange(ref m_AsyncOp, null, asyncOp) == asyncOp)
2294  {
2295  CompleteWebClientState();
2296  asyncOp.PostOperationCompleted(callback, eventArgs);
2297  }
2298  }
2299 
2300  private bool AnotherCallInProgress(int callNesting)
2301  {
2302  return callNesting > 1;
2303  }
2304 
2308  {
2309  if (this.OpenReadCompleted != null)
2310  {
2311  this.OpenReadCompleted(this, e);
2312  }
2313  }
2314 
2315  private void OpenReadOperationCompleted(object arg)
2316  {
2317  OnOpenReadCompleted((OpenReadCompletedEventArgs)arg);
2318  }
2319 
2320  private void OpenReadAsyncCallback(IAsyncResult result)
2321  {
2322  LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;
2323  AsyncOperation asyncOperation = (AsyncOperation)lazyAsyncResult.AsyncState;
2324  WebRequest request = (WebRequest)lazyAsyncResult.AsyncObject;
2325  Stream result2 = null;
2326  Exception exception = null;
2327  try
2328  {
2329  result2 = (m_WebResponse = GetWebResponse(request, result)).GetResponseStream();
2330  }
2331  catch (Exception ex)
2332  {
2333  if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
2334  {
2335  throw;
2336  }
2337  exception = ex;
2338  if (!(ex is WebException) && !(ex is SecurityException))
2339  {
2340  exception = new WebException(SR.GetString("net_webclient"), ex);
2341  }
2342  }
2343  OpenReadCompletedEventArgs eventArgs = new OpenReadCompletedEventArgs(result2, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2344  InvokeOperationCompleted(asyncOperation, openReadOperationCompleted, eventArgs);
2345  }
2346 
2351  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2352  public void OpenReadAsync(Uri address)
2353  {
2354  OpenReadAsync(address, null);
2355  }
2356 
2362  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2363  public void OpenReadAsync(Uri address, object userToken)
2364  {
2365  if (Logging.On)
2366  {
2367  Logging.Enter(Logging.Web, this, "OpenReadAsync", address);
2368  }
2369  if (address == null)
2370  {
2371  throw new ArgumentNullException("address");
2372  }
2373  InitWebClientAsync();
2374  ClearWebClientState();
2375  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2376  try
2377  {
2378  (m_WebRequest = GetWebRequest(GetUri(address))).BeginGetResponse(OpenReadAsyncCallback, asyncOperation);
2379  }
2380  catch (Exception ex)
2381  {
2382  Exception ex2 = ex;
2383  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2384  {
2385  throw;
2386  }
2387  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2388  {
2389  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2390  }
2391  OpenReadCompletedEventArgs eventArgs = new OpenReadCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
2392  InvokeOperationCompleted(asyncOperation, openReadOperationCompleted, eventArgs);
2393  }
2394  if (Logging.On)
2395  {
2396  Logging.Exit(Logging.Web, this, "OpenReadAsync", null);
2397  }
2398  }
2399 
2403  {
2404  if (this.OpenWriteCompleted != null)
2405  {
2406  this.OpenWriteCompleted(this, e);
2407  }
2408  }
2409 
2410  private void OpenWriteOperationCompleted(object arg)
2411  {
2412  OnOpenWriteCompleted((OpenWriteCompletedEventArgs)arg);
2413  }
2414 
2415  private void OpenWriteAsyncCallback(IAsyncResult result)
2416  {
2417  LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;
2418  AsyncOperation asyncOperation = (AsyncOperation)lazyAsyncResult.AsyncState;
2419  WebRequest webRequest = (WebRequest)lazyAsyncResult.AsyncObject;
2420  WebClientWriteStream result2 = null;
2421  Exception exception = null;
2422  try
2423  {
2424  result2 = new WebClientWriteStream(webRequest.EndGetRequestStream(result), webRequest, this);
2425  }
2426  catch (Exception ex)
2427  {
2428  if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
2429  {
2430  throw;
2431  }
2432  exception = ex;
2433  if (!(ex is WebException) && !(ex is SecurityException))
2434  {
2435  exception = new WebException(SR.GetString("net_webclient"), ex);
2436  }
2437  }
2438  OpenWriteCompletedEventArgs eventArgs = new OpenWriteCompletedEventArgs(result2, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2439  InvokeOperationCompleted(asyncOperation, openWriteOperationCompleted, eventArgs);
2440  }
2441 
2445  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2446  public void OpenWriteAsync(Uri address)
2447  {
2448  OpenWriteAsync(address, null, null);
2449  }
2450 
2455  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2456  public void OpenWriteAsync(Uri address, string method)
2457  {
2458  OpenWriteAsync(address, method, null);
2459  }
2460 
2467  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2468  public void OpenWriteAsync(Uri address, string method, object userToken)
2469  {
2470  if (Logging.On)
2471  {
2472  Logging.Enter(Logging.Web, this, "OpenWriteAsync", address + ", " + method);
2473  }
2474  if (address == null)
2475  {
2476  throw new ArgumentNullException("address");
2477  }
2478  if (method == null)
2479  {
2480  method = MapToDefaultMethod(address);
2481  }
2482  InitWebClientAsync();
2483  ClearWebClientState();
2484  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2485  try
2486  {
2487  m_Method = method;
2488  (m_WebRequest = GetWebRequest(GetUri(address))).BeginGetRequestStream(OpenWriteAsyncCallback, asyncOperation);
2489  }
2490  catch (Exception ex)
2491  {
2492  Exception ex2 = ex;
2493  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2494  {
2495  throw;
2496  }
2497  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2498  {
2499  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2500  }
2501  OpenWriteCompletedEventArgs eventArgs = new OpenWriteCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
2502  InvokeOperationCompleted(asyncOperation, openWriteOperationCompleted, eventArgs);
2503  }
2504  if (Logging.On)
2505  {
2506  Logging.Exit(Logging.Web, this, "OpenWriteAsync", null);
2507  }
2508  }
2509 
2513  {
2514  if (this.DownloadStringCompleted != null)
2515  {
2516  this.DownloadStringCompleted(this, e);
2517  }
2518  }
2519 
2520  private void DownloadStringOperationCompleted(object arg)
2521  {
2522  OnDownloadStringCompleted((DownloadStringCompletedEventArgs)arg);
2523  }
2524 
2525  private void DownloadStringAsyncCallback(byte[] returnBytes, Exception exception, object state)
2526  {
2527  AsyncOperation asyncOperation = (AsyncOperation)state;
2528  string result = null;
2529  try
2530  {
2531  if (returnBytes != null)
2532  {
2533  result = GetStringUsingEncoding(m_WebRequest, returnBytes);
2534  }
2535  }
2536  catch (Exception ex)
2537  {
2538  if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
2539  {
2540  throw;
2541  }
2542  exception = ex;
2543  }
2544  DownloadStringCompletedEventArgs eventArgs = new DownloadStringCompletedEventArgs(result, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2545  InvokeOperationCompleted(asyncOperation, downloadStringOperationCompleted, eventArgs);
2546  }
2547 
2552  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2553  public void DownloadStringAsync(Uri address)
2554  {
2555  DownloadStringAsync(address, null);
2556  }
2557 
2563  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2564  public void DownloadStringAsync(Uri address, object userToken)
2565  {
2566  if (Logging.On)
2567  {
2568  Logging.Enter(Logging.Web, this, "DownloadStringAsync", address);
2569  }
2570  if (address == null)
2571  {
2572  throw new ArgumentNullException("address");
2573  }
2574  InitWebClientAsync();
2575  ClearWebClientState();
2576  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2577  try
2578  {
2579  DownloadBits(m_WebRequest = GetWebRequest(GetUri(address)), null, DownloadStringAsyncCallback, asyncOperation);
2580  }
2581  catch (Exception ex)
2582  {
2583  Exception ex2 = ex;
2584  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2585  {
2586  throw;
2587  }
2588  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2589  {
2590  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2591  }
2592  DownloadStringAsyncCallback(null, ex2, asyncOperation);
2593  }
2594  if (Logging.On)
2595  {
2596  Logging.Exit(Logging.Web, this, "DownloadStringAsync", "");
2597  }
2598  }
2599 
2603  {
2604  if (this.DownloadDataCompleted != null)
2605  {
2606  this.DownloadDataCompleted(this, e);
2607  }
2608  }
2609 
2610  private void DownloadDataOperationCompleted(object arg)
2611  {
2612  OnDownloadDataCompleted((DownloadDataCompletedEventArgs)arg);
2613  }
2614 
2615  private void DownloadDataAsyncCallback(byte[] returnBytes, Exception exception, object state)
2616  {
2617  AsyncOperation asyncOperation = (AsyncOperation)state;
2618  DownloadDataCompletedEventArgs eventArgs = new DownloadDataCompletedEventArgs(returnBytes, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2619  InvokeOperationCompleted(asyncOperation, downloadDataOperationCompleted, eventArgs);
2620  }
2621 
2626  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2627  public void DownloadDataAsync(Uri address)
2628  {
2629  DownloadDataAsync(address, null);
2630  }
2631 
2637  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2638  public void DownloadDataAsync(Uri address, object userToken)
2639  {
2640  if (Logging.On)
2641  {
2642  Logging.Enter(Logging.Web, this, "DownloadDataAsync", address);
2643  }
2644  if (address == null)
2645  {
2646  throw new ArgumentNullException("address");
2647  }
2648  InitWebClientAsync();
2649  ClearWebClientState();
2650  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2651  try
2652  {
2653  DownloadBits(m_WebRequest = GetWebRequest(GetUri(address)), null, DownloadDataAsyncCallback, asyncOperation);
2654  }
2655  catch (Exception ex)
2656  {
2657  Exception ex2 = ex;
2658  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2659  {
2660  throw;
2661  }
2662  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2663  {
2664  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2665  }
2666  DownloadDataAsyncCallback(null, ex2, asyncOperation);
2667  }
2668  if (Logging.On)
2669  {
2670  Logging.Exit(Logging.Web, this, "DownloadDataAsync", null);
2671  }
2672  }
2673 
2677  {
2678  if (this.DownloadFileCompleted != null)
2679  {
2680  this.DownloadFileCompleted(this, e);
2681  }
2682  }
2683 
2684  private void DownloadFileOperationCompleted(object arg)
2685  {
2686  OnDownloadFileCompleted((AsyncCompletedEventArgs)arg);
2687  }
2688 
2689  private void DownloadFileAsyncCallback(byte[] returnBytes, Exception exception, object state)
2690  {
2691  AsyncOperation asyncOperation = (AsyncOperation)state;
2692  AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, m_Cancelled, asyncOperation.UserSuppliedState);
2693  InvokeOperationCompleted(asyncOperation, downloadFileOperationCompleted, eventArgs);
2694  }
2695 
2702  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2703  public void DownloadFileAsync(Uri address, string fileName)
2704  {
2705  DownloadFileAsync(address, fileName, null);
2706  }
2707 
2715  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2716  public void DownloadFileAsync(Uri address, string fileName, object userToken)
2717  {
2718  if (Logging.On)
2719  {
2720  Logging.Enter(Logging.Web, this, "DownloadFileAsync", address);
2721  }
2722  if (address == null)
2723  {
2724  throw new ArgumentNullException("address");
2725  }
2726  if (fileName == null)
2727  {
2728  throw new ArgumentNullException("fileName");
2729  }
2730  FileStream fileStream = null;
2731  InitWebClientAsync();
2732  ClearWebClientState();
2733  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2734  try
2735  {
2736  fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
2737  DownloadBits(m_WebRequest = GetWebRequest(GetUri(address)), fileStream, DownloadFileAsyncCallback, asyncOperation);
2738  }
2739  catch (Exception ex)
2740  {
2741  Exception ex2 = ex;
2742  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2743  {
2744  throw;
2745  }
2746  fileStream?.Close();
2747  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2748  {
2749  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2750  }
2751  DownloadFileAsyncCallback(null, ex2, asyncOperation);
2752  }
2753  if (Logging.On)
2754  {
2755  Logging.Exit(Logging.Web, this, "DownloadFileAsync", null);
2756  }
2757  }
2758 
2762  {
2763  if (this.UploadStringCompleted != null)
2764  {
2765  this.UploadStringCompleted(this, e);
2766  }
2767  }
2768 
2769  private void UploadStringOperationCompleted(object arg)
2770  {
2771  OnUploadStringCompleted((UploadStringCompletedEventArgs)arg);
2772  }
2773 
2774  private void StartDownloadAsync(UploadBitsState state)
2775  {
2776  try
2777  {
2778  DownloadBits(state.Request, null, state.DownloadCompletionDelegate, state.AsyncOp);
2779  }
2780  catch (Exception ex)
2781  {
2782  Exception ex2 = ex;
2783  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2784  {
2785  throw;
2786  }
2787  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2788  {
2789  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2790  }
2791  state.DownloadCompletionDelegate(null, ex2, state.AsyncOp);
2792  }
2793  }
2794 
2795  private void UploadStringAsyncWriteCallback(byte[] returnBytes, Exception exception, object state)
2796  {
2797  UploadBitsState uploadBitsState = (UploadBitsState)state;
2798  if (exception != null)
2799  {
2800  UploadStringCompletedEventArgs eventArgs = new UploadStringCompletedEventArgs(null, exception, m_Cancelled, uploadBitsState.AsyncOp.UserSuppliedState);
2801  InvokeOperationCompleted(uploadBitsState.AsyncOp, uploadStringOperationCompleted, eventArgs);
2802  }
2803  else
2804  {
2805  StartDownloadAsync(uploadBitsState);
2806  }
2807  }
2808 
2809  private void UploadStringAsyncReadCallback(byte[] returnBytes, Exception exception, object state)
2810  {
2811  AsyncOperation asyncOperation = (AsyncOperation)state;
2812  string result = null;
2813  try
2814  {
2815  if (returnBytes != null)
2816  {
2817  result = GetStringUsingEncoding(m_WebRequest, returnBytes);
2818  }
2819  }
2820  catch (Exception ex)
2821  {
2822  if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
2823  {
2824  throw;
2825  }
2826  exception = ex;
2827  }
2828  UploadStringCompletedEventArgs eventArgs = new UploadStringCompletedEventArgs(result, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2829  InvokeOperationCompleted(asyncOperation, uploadStringOperationCompleted, eventArgs);
2830  }
2831 
2839  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2840  public void UploadStringAsync(Uri address, string data)
2841  {
2842  UploadStringAsync(address, null, data, null);
2843  }
2844 
2852  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2853  public void UploadStringAsync(Uri address, string method, string data)
2854  {
2855  UploadStringAsync(address, method, data, null);
2856  }
2857 
2866  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2867  public void UploadStringAsync(Uri address, string method, string data, object userToken)
2868  {
2869  if (Logging.On)
2870  {
2871  Logging.Enter(Logging.Web, this, "UploadStringAsync", address);
2872  }
2873  if (address == null)
2874  {
2875  throw new ArgumentNullException("address");
2876  }
2877  if (data == null)
2878  {
2879  throw new ArgumentNullException("data");
2880  }
2881  if (method == null)
2882  {
2883  method = MapToDefaultMethod(address);
2884  }
2885  InitWebClientAsync();
2886  ClearWebClientState();
2887  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
2888  try
2889  {
2890  byte[] bytes = Encoding.GetBytes(data);
2891  m_Method = method;
2892  m_ContentLength = bytes.Length;
2893  UploadBits(m_WebRequest = GetWebRequest(GetUri(address)), null, bytes, 0, null, null, UploadStringAsyncWriteCallback, UploadStringAsyncReadCallback, asyncOperation);
2894  }
2895  catch (Exception ex)
2896  {
2897  Exception ex2 = ex;
2898  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
2899  {
2900  throw;
2901  }
2902  if (!(ex2 is WebException) && !(ex2 is SecurityException))
2903  {
2904  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
2905  }
2906  UploadStringCompletedEventArgs eventArgs = new UploadStringCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
2907  InvokeOperationCompleted(asyncOperation, uploadStringOperationCompleted, eventArgs);
2908  }
2909  if (Logging.On)
2910  {
2911  Logging.Exit(Logging.Web, this, "UploadStringAsync", null);
2912  }
2913  }
2914 
2918  {
2919  if (this.UploadDataCompleted != null)
2920  {
2921  this.UploadDataCompleted(this, e);
2922  }
2923  }
2924 
2925  private void UploadDataOperationCompleted(object arg)
2926  {
2927  OnUploadDataCompleted((UploadDataCompletedEventArgs)arg);
2928  }
2929 
2930  private void UploadDataAsyncWriteCallback(byte[] returnBytes, Exception exception, object state)
2931  {
2932  UploadBitsState uploadBitsState = (UploadBitsState)state;
2933  if (exception != null)
2934  {
2935  UploadDataCompletedEventArgs eventArgs = new UploadDataCompletedEventArgs(returnBytes, exception, m_Cancelled, uploadBitsState.AsyncOp.UserSuppliedState);
2936  InvokeOperationCompleted(uploadBitsState.AsyncOp, uploadDataOperationCompleted, eventArgs);
2937  }
2938  else
2939  {
2940  StartDownloadAsync(uploadBitsState);
2941  }
2942  }
2943 
2944  private void UploadDataAsyncReadCallback(byte[] returnBytes, Exception exception, object state)
2945  {
2946  AsyncOperation asyncOperation = (AsyncOperation)state;
2947  UploadDataCompletedEventArgs eventArgs = new UploadDataCompletedEventArgs(returnBytes, exception, m_Cancelled, asyncOperation.UserSuppliedState);
2948  InvokeOperationCompleted(asyncOperation, uploadDataOperationCompleted, eventArgs);
2949  }
2950 
2956  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2957  public void UploadDataAsync(Uri address, byte[] data)
2958  {
2959  UploadDataAsync(address, null, data, null);
2960  }
2961 
2968  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2969  public void UploadDataAsync(Uri address, string method, byte[] data)
2970  {
2971  UploadDataAsync(address, method, data, null);
2972  }
2973 
2981  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2982  public void UploadDataAsync(Uri address, string method, byte[] data, object userToken)
2983  {
2984  if (Logging.On)
2985  {
2986  Logging.Enter(Logging.Web, this, "UploadDataAsync", address + ", " + method);
2987  }
2988  if (address == null)
2989  {
2990  throw new ArgumentNullException("address");
2991  }
2992  if (data == null)
2993  {
2994  throw new ArgumentNullException("data");
2995  }
2996  if (method == null)
2997  {
2998  method = MapToDefaultMethod(address);
2999  }
3000  InitWebClientAsync();
3001  ClearWebClientState();
3002  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
3003  int chunkSize = 0;
3004  try
3005  {
3006  m_Method = method;
3007  m_ContentLength = data.Length;
3008  WebRequest request = m_WebRequest = GetWebRequest(GetUri(address));
3009  if (this.UploadProgressChanged != null)
3010  {
3011  chunkSize = (int)Math.Min(8192L, data.Length);
3012  }
3013  UploadBits(request, null, data, chunkSize, null, null, UploadDataAsyncWriteCallback, UploadDataAsyncReadCallback, asyncOperation);
3014  }
3015  catch (Exception ex)
3016  {
3017  Exception ex2 = ex;
3018  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
3019  {
3020  throw;
3021  }
3022  if (!(ex2 is WebException) && !(ex2 is SecurityException))
3023  {
3024  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
3025  }
3026  UploadDataCompletedEventArgs eventArgs = new UploadDataCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
3027  InvokeOperationCompleted(asyncOperation, uploadDataOperationCompleted, eventArgs);
3028  }
3029  if (Logging.On)
3030  {
3031  Logging.Exit(Logging.Web, this, "UploadDataAsync", null);
3032  }
3033  }
3034 
3038  {
3039  if (this.UploadFileCompleted != null)
3040  {
3041  this.UploadFileCompleted(this, e);
3042  }
3043  }
3044 
3045  private void UploadFileOperationCompleted(object arg)
3046  {
3047  OnUploadFileCompleted((UploadFileCompletedEventArgs)arg);
3048  }
3049 
3050  private void UploadFileAsyncWriteCallback(byte[] returnBytes, Exception exception, object state)
3051  {
3052  UploadBitsState uploadBitsState = (UploadBitsState)state;
3053  if (exception != null)
3054  {
3055  UploadFileCompletedEventArgs eventArgs = new UploadFileCompletedEventArgs(returnBytes, exception, m_Cancelled, uploadBitsState.AsyncOp.UserSuppliedState);
3056  InvokeOperationCompleted(uploadBitsState.AsyncOp, uploadFileOperationCompleted, eventArgs);
3057  }
3058  else
3059  {
3060  StartDownloadAsync(uploadBitsState);
3061  }
3062  }
3063 
3064  private void UploadFileAsyncReadCallback(byte[] returnBytes, Exception exception, object state)
3065  {
3066  AsyncOperation asyncOperation = (AsyncOperation)state;
3067  UploadFileCompletedEventArgs eventArgs = new UploadFileCompletedEventArgs(returnBytes, exception, m_Cancelled, asyncOperation.UserSuppliedState);
3068  InvokeOperationCompleted(asyncOperation, uploadFileOperationCompleted, eventArgs);
3069  }
3070 
3077  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3078  public void UploadFileAsync(Uri address, string fileName)
3079  {
3080  UploadFileAsync(address, null, fileName, null);
3081  }
3082 
3090  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3091  public void UploadFileAsync(Uri address, string method, string fileName)
3092  {
3093  UploadFileAsync(address, method, fileName, null);
3094  }
3095 
3104  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3105  public void UploadFileAsync(Uri address, string method, string fileName, object userToken)
3106  {
3107  if (Logging.On)
3108  {
3109  Logging.Enter(Logging.Web, this, "UploadFileAsync", address + ", " + method);
3110  }
3111  if (address == null)
3112  {
3113  throw new ArgumentNullException("address");
3114  }
3115  if (fileName == null)
3116  {
3117  throw new ArgumentNullException("fileName");
3118  }
3119  if (method == null)
3120  {
3121  method = MapToDefaultMethod(address);
3122  }
3123  InitWebClientAsync();
3124  ClearWebClientState();
3125  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
3126  FileStream fs = null;
3127  try
3128  {
3129  m_Method = method;
3130  byte[] formHeaderBytes = null;
3131  byte[] boundaryBytes = null;
3132  byte[] buffer = null;
3133  Uri uri = GetUri(address);
3134  bool needsHeaderAndBoundary = uri.Scheme != Uri.UriSchemeFile;
3135  OpenFileInternal(needsHeaderAndBoundary, fileName, ref fs, ref buffer, ref formHeaderBytes, ref boundaryBytes);
3136  UploadBits(m_WebRequest = GetWebRequest(uri), fs, buffer, 0, formHeaderBytes, boundaryBytes, UploadFileAsyncWriteCallback, UploadFileAsyncReadCallback, asyncOperation);
3137  }
3138  catch (Exception ex)
3139  {
3140  Exception ex2 = ex;
3141  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
3142  {
3143  throw;
3144  }
3145  fs?.Close();
3146  if (!(ex2 is WebException) && !(ex2 is SecurityException))
3147  {
3148  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
3149  }
3150  UploadFileCompletedEventArgs eventArgs = new UploadFileCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
3151  InvokeOperationCompleted(asyncOperation, uploadFileOperationCompleted, eventArgs);
3152  }
3153  if (Logging.On)
3154  {
3155  Logging.Exit(Logging.Web, this, "UploadFileAsync", null);
3156  }
3157  }
3158 
3162  {
3163  if (this.UploadValuesCompleted != null)
3164  {
3165  this.UploadValuesCompleted(this, e);
3166  }
3167  }
3168 
3169  private void UploadValuesOperationCompleted(object arg)
3170  {
3171  OnUploadValuesCompleted((UploadValuesCompletedEventArgs)arg);
3172  }
3173 
3174  private void UploadValuesAsyncWriteCallback(byte[] returnBytes, Exception exception, object state)
3175  {
3176  UploadBitsState uploadBitsState = (UploadBitsState)state;
3177  if (exception != null)
3178  {
3179  UploadValuesCompletedEventArgs eventArgs = new UploadValuesCompletedEventArgs(returnBytes, exception, m_Cancelled, uploadBitsState.AsyncOp.UserSuppliedState);
3180  InvokeOperationCompleted(uploadBitsState.AsyncOp, uploadValuesOperationCompleted, eventArgs);
3181  }
3182  else
3183  {
3184  StartDownloadAsync(uploadBitsState);
3185  }
3186  }
3187 
3188  private void UploadValuesAsyncReadCallback(byte[] returnBytes, Exception exception, object state)
3189  {
3190  AsyncOperation asyncOperation = (AsyncOperation)state;
3191  UploadValuesCompletedEventArgs eventArgs = new UploadValuesCompletedEventArgs(returnBytes, exception, m_Cancelled, asyncOperation.UserSuppliedState);
3192  InvokeOperationCompleted(asyncOperation, uploadValuesOperationCompleted, eventArgs);
3193  }
3194 
3200  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3201  public void UploadValuesAsync(Uri address, NameValueCollection data)
3202  {
3203  UploadValuesAsync(address, null, data, null);
3204  }
3205 
3213  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3214  public void UploadValuesAsync(Uri address, string method, NameValueCollection data)
3215  {
3216  UploadValuesAsync(address, method, data, null);
3217  }
3218 
3227  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3228  public void UploadValuesAsync(Uri address, string method, NameValueCollection data, object userToken)
3229  {
3230  if (Logging.On)
3231  {
3232  Logging.Enter(Logging.Web, this, "UploadValuesAsync", address + ", " + method);
3233  }
3234  if (address == null)
3235  {
3236  throw new ArgumentNullException("address");
3237  }
3238  if (data == null)
3239  {
3240  throw new ArgumentNullException("data");
3241  }
3242  if (method == null)
3243  {
3244  method = MapToDefaultMethod(address);
3245  }
3246  InitWebClientAsync();
3247  ClearWebClientState();
3248  AsyncOperation asyncOperation = m_AsyncOp = AsyncOperationManager.CreateOperation(userToken);
3249  int chunkSize = 0;
3250  try
3251  {
3252  byte[] array = UploadValuesInternal(data);
3253  m_Method = method;
3254  WebRequest request = m_WebRequest = GetWebRequest(GetUri(address));
3255  if (this.UploadProgressChanged != null)
3256  {
3257  chunkSize = (int)Math.Min(8192L, array.Length);
3258  }
3259  UploadBits(request, null, array, chunkSize, null, null, UploadValuesAsyncWriteCallback, UploadValuesAsyncReadCallback, asyncOperation);
3260  }
3261  catch (Exception ex)
3262  {
3263  Exception ex2 = ex;
3264  if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
3265  {
3266  throw;
3267  }
3268  if (!(ex2 is WebException) && !(ex2 is SecurityException))
3269  {
3270  ex2 = new WebException(SR.GetString("net_webclient"), ex2);
3271  }
3272  UploadValuesCompletedEventArgs eventArgs = new UploadValuesCompletedEventArgs(null, ex2, m_Cancelled, asyncOperation.UserSuppliedState);
3273  InvokeOperationCompleted(asyncOperation, uploadValuesOperationCompleted, eventArgs);
3274  }
3275  if (Logging.On)
3276  {
3277  Logging.Exit(Logging.Web, this, "UploadValuesAsync", null);
3278  }
3279  }
3280 
3282  public void CancelAsync()
3283  {
3284  WebRequest webRequest = m_WebRequest;
3285  m_Cancelled = true;
3286  AbortRequest(webRequest);
3287  }
3288 
3294  [ComVisible(false)]
3295  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3296  public Task<string> DownloadStringTaskAsync(string address)
3297  {
3298  return DownloadStringTaskAsync(GetUri(address));
3299  }
3300 
3306  [ComVisible(false)]
3307  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3309  {
3311  DownloadStringCompletedEventHandler handler = null;
3312  handler = delegate(object sender, DownloadStringCompletedEventArgs e)
3313  {
3314  HandleCompletion(tcs, e, (DownloadStringCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, DownloadStringCompletedEventHandler completion)
3315  {
3316  webClient.DownloadStringCompleted -= completion;
3317  });
3318  };
3319  DownloadStringCompleted += handler;
3320  try
3321  {
3322  DownloadStringAsync(address, tcs);
3323  }
3324  catch
3325  {
3326  DownloadStringCompleted -= handler;
3327  throw;
3328  }
3329  return tcs.Task;
3330  }
3331 
3337  [ComVisible(false)]
3338  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3339  public Task<Stream> OpenReadTaskAsync(string address)
3340  {
3341  return OpenReadTaskAsync(GetUri(address));
3342  }
3343 
3349  [ComVisible(false)]
3350  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3352  {
3354  OpenReadCompletedEventHandler handler = null;
3355  handler = delegate(object sender, OpenReadCompletedEventArgs e)
3356  {
3357  HandleCompletion(tcs, e, (OpenReadCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, OpenReadCompletedEventHandler completion)
3358  {
3359  webClient.OpenReadCompleted -= completion;
3360  });
3361  };
3362  OpenReadCompleted += handler;
3363  try
3364  {
3365  OpenReadAsync(address, tcs);
3366  }
3367  catch
3368  {
3369  OpenReadCompleted -= handler;
3370  throw;
3371  }
3372  return tcs.Task;
3373  }
3374 
3380  [ComVisible(false)]
3381  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3382  public Task<Stream> OpenWriteTaskAsync(string address)
3383  {
3384  return OpenWriteTaskAsync(GetUri(address), null);
3385  }
3386 
3392  [ComVisible(false)]
3393  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3395  {
3396  return OpenWriteTaskAsync(address, null);
3397  }
3398 
3405  [ComVisible(false)]
3406  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3407  public Task<Stream> OpenWriteTaskAsync(string address, string method)
3408  {
3409  return OpenWriteTaskAsync(GetUri(address), method);
3410  }
3411 
3418  [ComVisible(false)]
3419  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3420  public Task<Stream> OpenWriteTaskAsync(Uri address, string method)
3421  {
3423  OpenWriteCompletedEventHandler handler = null;
3424  handler = delegate(object sender, OpenWriteCompletedEventArgs e)
3425  {
3426  HandleCompletion(tcs, e, (OpenWriteCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, OpenWriteCompletedEventHandler completion)
3427  {
3428  webClient.OpenWriteCompleted -= completion;
3429  });
3430  };
3431  OpenWriteCompleted += handler;
3432  try
3433  {
3434  OpenWriteAsync(address, method, tcs);
3435  }
3436  catch
3437  {
3438  OpenWriteCompleted -= handler;
3439  throw;
3440  }
3441  return tcs.Task;
3442  }
3443 
3452  [ComVisible(false)]
3453  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3454  public Task<string> UploadStringTaskAsync(string address, string data)
3455  {
3456  return UploadStringTaskAsync(address, null, data);
3457  }
3458 
3467  [ComVisible(false)]
3468  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3469  public Task<string> UploadStringTaskAsync(Uri address, string data)
3470  {
3471  return UploadStringTaskAsync(address, null, data);
3472  }
3473 
3484  [ComVisible(false)]
3485  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3486  public Task<string> UploadStringTaskAsync(string address, string method, string data)
3487  {
3488  return UploadStringTaskAsync(GetUri(address), method, data);
3489  }
3490 
3501  [ComVisible(false)]
3502  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3503  public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
3504  {
3506  UploadStringCompletedEventHandler handler = null;
3507  handler = delegate(object sender, UploadStringCompletedEventArgs e)
3508  {
3509  HandleCompletion(tcs, e, (UploadStringCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, UploadStringCompletedEventHandler completion)
3510  {
3511  webClient.UploadStringCompleted -= completion;
3512  });
3513  };
3514  UploadStringCompleted += handler;
3515  try
3516  {
3517  UploadStringAsync(address, method, data, tcs);
3518  }
3519  catch
3520  {
3521  UploadStringCompleted -= handler;
3522  throw;
3523  }
3524  return tcs.Task;
3525  }
3526 
3532  [ComVisible(false)]
3533  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3534  public Task<byte[]> DownloadDataTaskAsync(string address)
3535  {
3536  return DownloadDataTaskAsync(GetUri(address));
3537  }
3538 
3544  [ComVisible(false)]
3545  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3547  {
3549  DownloadDataCompletedEventHandler handler = null;
3550  handler = delegate(object sender, DownloadDataCompletedEventArgs e)
3551  {
3552  HandleCompletion(tcs, e, (DownloadDataCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, DownloadDataCompletedEventHandler completion)
3553  {
3554  webClient.DownloadDataCompleted -= completion;
3555  });
3556  };
3557  DownloadDataCompleted += handler;
3558  try
3559  {
3560  DownloadDataAsync(address, tcs);
3561  }
3562  catch
3563  {
3564  DownloadDataCompleted -= handler;
3565  throw;
3566  }
3567  return tcs.Task;
3568  }
3569 
3577  [ComVisible(false)]
3578  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3579  public Task DownloadFileTaskAsync(string address, string fileName)
3580  {
3581  return DownloadFileTaskAsync(GetUri(address), fileName);
3582  }
3583 
3591  [ComVisible(false)]
3592  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3593  public Task DownloadFileTaskAsync(Uri address, string fileName)
3594  {
3596  AsyncCompletedEventHandler handler = null;
3597  handler = delegate(object sender, AsyncCompletedEventArgs e)
3598  {
3599  HandleCompletion(tcs, e, (AsyncCompletedEventArgs args) => null, handler, delegate(WebClient webClient, AsyncCompletedEventHandler completion)
3600  {
3601  webClient.DownloadFileCompleted -= completion;
3602  });
3603  };
3604  DownloadFileCompleted += handler;
3605  try
3606  {
3607  DownloadFileAsync(address, fileName, tcs);
3608  }
3609  catch
3610  {
3611  DownloadFileCompleted -= handler;
3612  throw;
3613  }
3614  return tcs.Task;
3615  }
3616 
3623  [ComVisible(false)]
3624  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3625  public Task<byte[]> UploadDataTaskAsync(string address, byte[] data)
3626  {
3627  return UploadDataTaskAsync(GetUri(address), null, data);
3628  }
3629 
3636  [ComVisible(false)]
3637  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3638  public Task<byte[]> UploadDataTaskAsync(Uri address, byte[] data)
3639  {
3640  return UploadDataTaskAsync(address, null, data);
3641  }
3642 
3650  [ComVisible(false)]
3651  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3652  public Task<byte[]> UploadDataTaskAsync(string address, string method, byte[] data)
3653  {
3654  return UploadDataTaskAsync(GetUri(address), method, data);
3655  }
3656 
3664  [ComVisible(false)]
3665  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3666  public Task<byte[]> UploadDataTaskAsync(Uri address, string method, byte[] data)
3667  {
3669  UploadDataCompletedEventHandler handler = null;
3670  handler = delegate(object sender, UploadDataCompletedEventArgs e)
3671  {
3672  HandleCompletion(tcs, e, (UploadDataCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, UploadDataCompletedEventHandler completion)
3673  {
3674  webClient.UploadDataCompleted -= completion;
3675  });
3676  };
3677  UploadDataCompleted += handler;
3678  try
3679  {
3680  UploadDataAsync(address, method, data, tcs);
3681  }
3682  catch
3683  {
3684  UploadDataCompleted -= handler;
3685  throw;
3686  }
3687  return tcs.Task;
3688  }
3689 
3697  [ComVisible(false)]
3698  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3699  public Task<byte[]> UploadFileTaskAsync(string address, string fileName)
3700  {
3701  return UploadFileTaskAsync(GetUri(address), null, fileName);
3702  }
3703 
3711  [ComVisible(false)]
3712  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3713  public Task<byte[]> UploadFileTaskAsync(Uri address, string fileName)
3714  {
3715  return UploadFileTaskAsync(address, null, fileName);
3716  }
3717 
3726  [ComVisible(false)]
3727  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3728  public Task<byte[]> UploadFileTaskAsync(string address, string method, string fileName)
3729  {
3730  return UploadFileTaskAsync(GetUri(address), method, fileName);
3731  }
3732 
3741  [ComVisible(false)]
3742  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3743  public Task<byte[]> UploadFileTaskAsync(Uri address, string method, string fileName)
3744  {
3746  UploadFileCompletedEventHandler handler = null;
3747  handler = delegate(object sender, UploadFileCompletedEventArgs e)
3748  {
3749  HandleCompletion(tcs, e, (UploadFileCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, UploadFileCompletedEventHandler completion)
3750  {
3751  webClient.UploadFileCompleted -= completion;
3752  });
3753  };
3754  UploadFileCompleted += handler;
3755  try
3756  {
3757  UploadFileAsync(address, method, fileName, tcs);
3758  }
3759  catch
3760  {
3761  UploadFileCompleted -= handler;
3762  throw;
3763  }
3764  return tcs.Task;
3765  }
3766 
3773  [ComVisible(false)]
3774  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3776  {
3777  return UploadValuesTaskAsync(GetUri(address), null, data);
3778  }
3779 
3788  [ComVisible(false)]
3789  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3790  public Task<byte[]> UploadValuesTaskAsync(string address, string method, NameValueCollection data)
3791  {
3792  return UploadValuesTaskAsync(GetUri(address), method, data);
3793  }
3794 
3801  [ComVisible(false)]
3802  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3804  {
3805  return UploadValuesTaskAsync(address, null, data);
3806  }
3807 
3816  [ComVisible(false)]
3817  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3818  public Task<byte[]> UploadValuesTaskAsync(Uri address, string method, NameValueCollection data)
3819  {
3821  UploadValuesCompletedEventHandler handler = null;
3822  handler = delegate(object sender, UploadValuesCompletedEventArgs e)
3823  {
3824  HandleCompletion(tcs, e, (UploadValuesCompletedEventArgs args) => args.Result, handler, delegate(WebClient webClient, UploadValuesCompletedEventHandler completion)
3825  {
3826  webClient.UploadValuesCompleted -= completion;
3827  });
3828  };
3829  UploadValuesCompleted += handler;
3830  try
3831  {
3832  UploadValuesAsync(address, method, data, tcs);
3833  }
3834  catch
3835  {
3836  UploadValuesCompleted -= handler;
3837  throw;
3838  }
3839  return tcs.Task;
3840  }
3841 
3842  private void HandleCompletion<TAsyncCompletedEventArgs, TCompletionDelegate, T>(TaskCompletionSource<T> tcs, TAsyncCompletedEventArgs e, Func<TAsyncCompletedEventArgs, T> getResult, TCompletionDelegate handler, Action<WebClient, TCompletionDelegate> unregisterHandler) where TAsyncCompletedEventArgs : AsyncCompletedEventArgs
3843  {
3844  if (e.UserState == tcs)
3845  {
3846  try
3847  {
3848  unregisterHandler(this, handler);
3849  }
3850  finally
3851  {
3852  if (e.Error != null)
3853  {
3854  tcs.TrySetException(e.Error);
3855  }
3856  else if (e.Cancelled)
3857  {
3858  tcs.TrySetCanceled();
3859  }
3860  else
3861  {
3862  tcs.TrySetResult(getResult(e));
3863  }
3864  }
3865  }
3866  }
3867 
3871  {
3872  if (this.DownloadProgressChanged != null)
3873  {
3874  this.DownloadProgressChanged(this, e);
3875  }
3876  }
3877 
3881  {
3882  if (this.UploadProgressChanged != null)
3883  {
3884  this.UploadProgressChanged(this, e);
3885  }
3886  }
3887 
3888  private void ReportDownloadProgressChanged(object arg)
3889  {
3890  OnDownloadProgressChanged((DownloadProgressChangedEventArgs)arg);
3891  }
3892 
3893  private void ReportUploadProgressChanged(object arg)
3894  {
3895  OnUploadProgressChanged((UploadProgressChangedEventArgs)arg);
3896  }
3897 
3898  private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress)
3899  {
3900  if (asyncOp != null && progress.BytesSent + progress.BytesReceived > 0)
3901  {
3902  if (progress.HasUploadPhase)
3903  {
3904  int progressPercentage = (int)((progress.TotalBytesToReceive >= 0 || progress.BytesReceived != 0L) ? ((progress.TotalBytesToSend < 0) ? 50 : ((progress.TotalBytesToReceive == 0L) ? 100 : (50 * progress.BytesReceived / progress.TotalBytesToReceive + 50))) : ((progress.TotalBytesToSend >= 0) ? ((progress.TotalBytesToSend == 0L) ? 50 : (50 * progress.BytesSent / progress.TotalBytesToSend)) : 0));
3905  asyncOp.Post(reportUploadProgressChanged, new UploadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState, progress.BytesSent, progress.TotalBytesToSend, progress.BytesReceived, progress.TotalBytesToReceive));
3906  }
3907  else
3908  {
3909  int progressPercentage = (int)((progress.TotalBytesToReceive >= 0) ? ((progress.TotalBytesToReceive == 0L) ? 100 : (100 * progress.BytesReceived / progress.TotalBytesToReceive)) : 0);
3910  asyncOp.Post(reportDownloadProgressChanged, new DownloadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState, progress.BytesReceived, progress.TotalBytesToReceive));
3911  }
3912  }
3913  }
3914  }
3915 }
UriKind
Defines the kinds of T:System.Uris for the M:System.Uri.IsWellFormedUriString(System....
Definition: UriKind.cs:5
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
Stream Result
Gets a readable stream that contains data downloaded by a Overload:System.Net.WebClient....
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
Definition: CultureInfo.cs:263
Provides concurrency management for classes that support asynchronous method calls....
DownloadProgressChangedEventHandler DownloadProgressChanged
Occurs when an asynchronous download operation successfully transfers some or all of the data.
Definition: WebClient.cs:798
Task< byte[]> UploadFileTaskAsync(string address, string fileName)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
Definition: WebClient.cs:3699
Task< Stream > OpenWriteTaskAsync(string address, string method)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3407
The exception that is thrown when an error occurs while accessing the network through a pluggable pro...
Definition: WebException.cs:9
string UploadString(Uri address, string data)
Uploads the specified string to the specified resource, using the POST method.
Definition: WebClient.cs:1658
abstract void Write(byte[] buffer, int offset, int count)
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the...
string Result
Gets the server reply to a string upload operation that is started by calling an Overload:System....
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
unsafe string GetString(byte *bytes, int byteCount)
When overridden in a derived class, decodes a specified number of bytes starting at a specified addre...
Definition: Encoding.cs:1918
abstract int Read([In] [Out] byte[] buffer, int offset, int count)
When overridden in a derived class, reads a sequence of bytes from the current stream and advances th...
string UploadString(Uri address, string method, string data)
Uploads the specified string to the specified resource, using the specified method.
Definition: WebClient.cs:1688
Represents a collection of associated T:System.String keys and T:System.String values that can be acc...
WebClient()
Initializes a new instance of the T:System.Net.WebClient class.
Definition: WebClient.cs:804
Stream Result
Gets a writable stream that is used to send data to a server.
Task DownloadFileTaskAsync(string address, string fileName)
Downloads the specified resource to a local file as an asynchronous operation using a task object.
Definition: WebClient.cs:3579
delegate void SendOrPostCallback(object state)
Represents a method to be called when a message is to be dispatched to a synchronization context.
Stream OpenRead(string address)
Opens a readable stream for the data downloaded from a resource with the URI specified as a T:System....
Definition: WebClient.cs:1070
Task< string > UploadStringTaskAsync(string address, string method, string data)
Uploads the specified string to the specified resource as an asynchronous operation using a task obje...
Definition: WebClient.cs:3486
virtual byte [] GetBytes(char[] chars)
When overridden in a derived class, encodes all the characters in the specified character array into ...
Definition: Encoding.cs:1576
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
void UploadStringAsync(Uri address, string method, string data, object userToken)
Uploads the specified string to the specified resource. This method does not block the calling thread...
Definition: WebClient.cs:2867
The exception that is thrown when the execution stack overflows because it contains too many nested m...
virtual WebResponse GetWebResponse(WebRequest request)
Returns the T:System.Net.WebResponse for the specified T:System.Net.WebRequest.
Definition: WebClient.cs:896
Provides data for the E:System.Net.WebClient.UploadDataCompleted event.
Tracks the lifetime of an asynchronous operation.
delegate void DownloadDataCompletedEventHandler(object sender, DownloadDataCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.DownloadDataCompleted event of a T:...
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
virtual void OnUploadValuesCompleted(UploadValuesCompletedEventArgs e)
Raises the E:System.Net.WebClient.UploadValuesCompleted event.
Definition: WebClient.cs:3161
delegate void UploadDataCompletedEventHandler(object sender, UploadDataCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.UploadDataCompleted event of a T:Sy...
abstract bool CanSeek
When overridden in a derived class, gets a value indicating whether the current stream supports seeki...
Definition: Stream.cs:587
void OpenReadAsync(Uri address, object userToken)
Opens a readable stream containing the specified resource. This method does not block the calling thr...
Definition: WebClient.cs:2363
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
static Encoding Default
Gets an encoding for the operating system's current ANSI code page.
Definition: Encoding.cs:959
string UploadString(string address, string method, string data)
Uploads the specified string to the specified resource, using the specified method.
Definition: WebClient.cs:1671
virtual int WriteTimeout
Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write befor...
Definition: Stream.cs:665
void UploadValuesAsync(Uri address, NameValueCollection data)
Uploads the data in the specified name/value collection to the resource identified by the specified U...
Definition: WebClient.cs:3201
virtual string [] AllKeys
Gets all the keys in the T:System.Collections.Specialized.NameValueCollection.
FileMode
Specifies how the operating system should open a file.
Definition: FileMode.cs:8
Stream OpenWrite(Uri address)
Opens a stream for writing data to the specified resource.
Definition: WebClient.cs:1145
EditorBrowsableState
Specifies the browsable state of a property or method from within an editor.
virtual RequestCachePolicy CachePolicy
Gets or sets the cache policy for this request.
Definition: WebRequest.cs:186
static Encoding Unicode
Gets an encoding for the UTF-16 format using the little endian byte order.
Definition: Encoding.cs:975
Task< byte[]> UploadValuesTaskAsync(Uri address, string method, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI as an asy...
Definition: WebClient.cs:3818
Makes a request to a Uniform Resource Identifier (URI). This is an abstract class.
Definition: WebRequest.cs:21
delegate void DownloadProgressChangedEventHandler(object sender, DownloadProgressChangedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.DownloadProgressChanged event of a ...
static sbyte Min(sbyte val1, sbyte val2)
Returns the smaller of two 8-bit signed integers.
Definition: Math.cs:762
delegate void UploadStringCompletedEventHandler(object sender, UploadStringCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.UploadStringCompleted event of a T:...
Task< string > UploadStringTaskAsync(Uri address, string method, string data)
Uploads the specified string to the specified resource as an asynchronous operation using a task obje...
Definition: WebClient.cs:3503
Stream OpenWrite(string address)
Opens a stream for writing data to the specified resource.
Definition: WebClient.cs:1131
Task< Stream > OpenWriteTaskAsync(Uri address)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3394
Definition: __Canon.cs:3
DownloadStringCompletedEventHandler DownloadStringCompleted
Occurs when an asynchronous resource-download operation completes.
Definition: WebClient.cs:777
string Scheme
Gets the scheme name for this URI.
Definition: Uri.cs:702
abstract bool CanWrite
When overridden in a derived class, gets a value indicating whether the current stream supports writi...
Definition: Stream.cs:610
Task< Stream > OpenWriteTaskAsync(Uri address, string method)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3420
Task< Stream > OpenReadTaskAsync(Uri address)
Opens a readable stream containing the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3351
Provides common methods for sending data to and receiving data from a resource identified by a URI.
Definition: WebClient.cs:17
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
void UploadDataAsync(Uri address, string method, byte[] data)
Uploads a data buffer to a resource identified by a URI, using the specified method....
Definition: WebClient.cs:2969
Task< Stream > OpenWriteTaskAsync(string address)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3382
void UploadDataAsync(Uri address, byte[] data)
Uploads a data buffer to a resource identified by a URI, using the POST method. This method does not ...
Definition: WebClient.cs:2957
virtual WebRequest GetWebRequest(Uri address)
Returns a T:System.Net.WebRequest object for the specified resource.
Definition: WebClient.cs:866
Task< byte[]> UploadFileTaskAsync(Uri address, string fileName)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
Definition: WebClient.cs:3713
virtual void OnOpenWriteCompleted(OpenWriteCompletedEventArgs e)
Raises the E:System.Net.WebClient.OpenWriteCompleted event.
Definition: WebClient.cs:2402
Task< string > DownloadStringTaskAsync(string address)
Downloads the resource as a T:System.String from the URI specified as an asynchronous operation using...
Definition: WebClient.cs:3296
static string GetFileName(string path)
Returns the file name and extension of the specified path string.
Definition: Path.cs:914
byte [] Result
Gets the server reply to a data upload operation started by calling an Overload:System....
NameValueCollection QueryString
Gets or sets a collection of query name/value pairs associated with the request.
Definition: WebClient.cs:686
virtual void Close()
When overridden by a descendant class, closes the response stream.
Definition: WebResponse.cs:150
Provides data for the E:System.Net.WebClient.OpenReadCompleted event.
virtual void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
Raises the E:System.Net.WebClient.DownloadProgressChanged event.
Definition: WebClient.cs:3870
void OpenWriteAsync(Uri address)
Opens a stream for writing data to the specified resource. This method does not block the calling thr...
Definition: WebClient.cs:2446
static Encoding GetEncoding(int codepage)
Returns the encoding associated with the specified code page identifier.
Definition: Encoding.cs:1249
string BaseAddress
Gets or sets the base URI for requests made by a T:System.Net.WebClient.
Definition: WebClient.cs:603
byte [] DownloadData(string address)
Downloads the resource as a T:System.Byte array from the URI specified.
Definition: WebClient.cs:916
WriteStreamClosedEventHandler WriteStreamClosed
Occurs when an asynchronous operation to write data to a resource using a write stream is closed.
Definition: WebClient.cs:761
byte [] UploadFile(string address, string method, string fileName)
Uploads the specified local file to the specified resource, using the specified method.
Definition: WebClient.cs:1426
A type representing a date and time value.
void UploadValuesAsync(Uri address, string method, NameValueCollection data, object userToken)
Uploads the data in the specified name/value collection to the resource identified by the specified U...
Definition: WebClient.cs:3228
byte [] UploadFile(string address, string fileName)
Uploads the specified local file to a resource with the specified URI.
Definition: WebClient.cs:1397
RequestCachePolicy CachePolicy
Gets or sets the application's cache policy for any resources obtained by this WebClient instance usi...
Definition: WebClient.cs:741
abstract void SetLength(long value)
When overridden in a derived class, sets the length of the current stream.
SeekOrigin
Specifies the position in a stream to use for seeking.
Definition: SeekOrigin.cs:9
void DownloadFileAsync(Uri address, string fileName, object userToken)
Downloads, to a local file, the resource with the specified URI. This method does not block the calli...
Definition: WebClient.cs:2716
static Encoding ASCII
Gets an encoding for the ASCII (7-bit) character set.
Definition: Encoding.cs:920
virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
Begins an asynchronous read operation. (Consider using M:System.IO.Stream.ReadAsync(System....
Definition: Stream.cs:928
void UploadFileAsync(Uri address, string fileName)
Uploads the specified local file to the specified resource, using the POST method....
Definition: WebClient.cs:3078
Contains protocol headers associated with a request or response.
static Encoding BigEndianUnicode
Gets an encoding for the UTF-16 format that uses the big endian byte order.
Definition: Encoding.cs:991
WebHeaderCollection Headers
Gets or sets a collection of header name/value pairs associated with the request.
Definition: WebClient.cs:668
AsyncCompletedEventHandler DownloadFileCompleted
Occurs when an asynchronous file download operation completes.
Definition: WebClient.cs:783
Stream OpenWrite(Uri address, string method)
Opens a stream for writing data to the specified resource, by using the specified method.
Definition: WebClient.cs:1171
bool AllowWriteStreamBuffering
Gets or sets a value that indicates whether to buffer the data written to the Internet resource for a...
Definition: WebClient.cs:575
virtual void OnOpenReadCompleted(OpenReadCompletedEventArgs e)
Raises the E:System.Net.WebClient.OpenReadCompleted event.
Definition: WebClient.cs:2307
Provides data for the MethodNameCompleted event.
void OpenWriteAsync(Uri address, string method)
Opens a stream for writing data to the specified resource. This method does not block the calling thr...
Definition: WebClient.cs:2456
abstract bool CanRead
When overridden in a derived class, gets a value indicating whether the current stream supports readi...
Definition: Stream.cs:577
delegate void OpenWriteCompletedEventHandler(object sender, OpenWriteCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.OpenWriteCompleted event of a T:Sys...
static Encoding UTF32
Gets an encoding for the UTF-32 format using the little endian byte order.
Definition: Encoding.cs:1039
SecurityAction
Specifies the security actions that can be performed using declarative security.
virtual void OnDownloadDataCompleted(DownloadDataCompletedEventArgs e)
Raises the E:System.Net.WebClient.DownloadDataCompleted event.
Definition: WebClient.cs:2602
void UploadStringAsync(Uri address, string method, string data)
Uploads the specified string to the specified resource. This method does not block the calling thread...
Definition: WebClient.cs:2853
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
Definition: Stream.cs:855
Provides a response from a Uniform Resource Identifier (URI). This is an abstract class.
Definition: WebResponse.cs:10
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
UploadProgressChangedEventHandler UploadProgressChanged
Occurs when an asynchronous upload operation successfully transfers some or all of the data.
Definition: WebClient.cs:801
void DownloadFile(Uri address, string fileName)
Downloads the resource with the specified URI to a local file.
Definition: WebClient.cs:1007
StringBuilder Append(char value, int repeatCount)
Appends a specified number of copies of the string representation of a Unicode character to this inst...
void DownloadDataAsync(Uri address)
Downloads the resource as a T:System.Byte array from the URI specified as an asynchronous operation.
Definition: WebClient.cs:2627
static readonly Stream Null
A Stream with no backing store.
Definition: Stream.cs:562
virtual Stream GetRequestStream()
When overridden in a descendant class, returns a T:System.IO.Stream for writing data to the Internet ...
Definition: WebRequest.cs:717
void Dispose()
Releases all resources used by the T:System.ComponentModel.Component.
Definition: Component.cs:101
byte [] UploadFile(Uri address, string method, string fileName)
Uploads the specified local file to the specified resource, using the specified method.
Definition: WebClient.cs:1439
void DownloadStringAsync(Uri address)
Downloads the resource specified as a T:System.Uri. This method does not block the calling thread.
Definition: WebClient.cs:2553
virtual string Method
When overridden in a descendant class, gets or sets the protocol method to use in this request.
Definition: WebRequest.cs:202
delegate void UploadProgressChangedEventHandler(object sender, UploadProgressChangedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.UploadProgressChanged event of a T:...
byte [] UploadValues(string address, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI.
Definition: WebClient.cs:1538
Provides data for the E:System.Net.WebClient.UploadStringCompleted event.
virtual int ReadTimeout
Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before...
Definition: Stream.cs:646
Task< byte[]> UploadValuesTaskAsync(string address, string method, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI as an asy...
Definition: WebClient.cs:3790
void DownloadDataAsync(Uri address, object userToken)
Downloads the resource as a T:System.Byte array from the URI specified as an asynchronous operation.
Definition: WebClient.cs:2638
byte [] UploadData(Uri address, string method, byte[] data)
Uploads a data buffer to the specified resource, using the specified method.
Definition: WebClient.cs:1271
UploadValuesCompletedEventHandler UploadValuesCompleted
Occurs when an asynchronous upload of a name/value collection completes.
Definition: WebClient.cs:795
Task< byte[]> UploadValuesTaskAsync(Uri address, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI as an asy...
Definition: WebClient.cs:3803
Provides storage for multiple credentials.
delegate void WriteStreamClosedEventHandler(object sender, WriteStreamClosedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.WriteStreamClosed event of a T:Syst...
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
Provides data for the E:System.Net.WebClient.OpenWriteCompleted event.
Task DownloadFileTaskAsync(Uri address, string fileName)
Downloads the specified resource to a local file as an asynchronous operation using a task object.
Definition: WebClient.cs:3593
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
byte [] UploadFile(Uri address, string fileName)
Uploads the specified local file to a resource with the specified URI.
Definition: WebClient.cs:1413
byte [] UploadData(string address, byte[] data)
Uploads a data buffer to a resource identified by a URI.
Definition: WebClient.cs:1225
void UploadFileAsync(Uri address, string method, string fileName, object userToken)
Uploads the specified local file to the specified resource, using the POST method....
Definition: WebClient.cs:3105
Task< byte[]> UploadValuesTaskAsync(string address, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI as an asy...
Definition: WebClient.cs:3775
Task< byte[]> UploadDataTaskAsync(Uri address, byte[] data)
Uploads a data buffer that contains a T:System.Byte array to the URI specified as an asynchronous ope...
Definition: WebClient.cs:3638
void UploadStringAsync(Uri address, string data)
Uploads the specified string to the specified resource. This method does not block the calling thread...
Definition: WebClient.cs:2840
static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
Copies a specified number of bytes from a source array starting at a particular offset to a destinati...
Task< string > UploadStringTaskAsync(Uri address, string data)
Uploads the specified string to the specified resource as an asynchronous operation using a task obje...
Definition: WebClient.cs:3469
static int Increment(ref int location)
Increments a specified variable and stores the result, as an atomic operation.
Definition: Interlocked.cs:18
abstract void Flush()
When overridden in a derived class, clears all buffers for this stream and causes any buffered data t...
void DownloadFileAsync(Uri address, string fileName)
Downloads, to a local file, the resource with the specified URI. This method does not block the calli...
Definition: WebClient.cs:2703
static ICredentials DefaultCredentials
Gets the system credentials of the application.
void UploadFileAsync(Uri address, string method, string fileName)
Uploads the specified local file to the specified resource, using the POST method....
Definition: WebClient.cs:3091
UploadStringCompletedEventHandler UploadStringCompleted
Occurs when an asynchronous string-upload operation completes.
Definition: WebClient.cs:786
byte [] Result
Gets the server reply to a data upload operation started by calling an Overload:System....
Represents the producer side of a T:System.Threading.Tasks.Task`1 unbound to a delegate,...
Provides the base authentication interface for retrieving credentials for Web client authentication.
Definition: ICredentials.cs:5
virtual void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
Raises the E:System.Net.WebClient.DownloadStringCompleted event.
Definition: WebClient.cs:2512
Provides the base implementation for the T:System.ComponentModel.IComponent interface and enables obj...
Definition: Component.cs:9
UploadFileCompletedEventHandler UploadFileCompleted
Occurs when an asynchronous file-upload operation completes.
Definition: WebClient.cs:792
virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
Returns the T:System.Net.WebResponse for the specified T:System.Net.WebRequest using the specified T:...
Definition: WebClient.cs:905
The exception that is thrown when there is not enough memory to continue the execution of a program.
string Result
Gets the data that is downloaded by a Overload:System.Net.WebClient.DownloadStringAsync method.
static string GetFullPath(string path)
Returns the absolute path for the specified path string.
Definition: Path.cs:446
void DownloadFile(string address, string fileName)
Downloads the resource with the specified URI to a local file.
Definition: WebClient.cs:991
bool? UseDefaultCredentials
Gets or sets a T:System.Boolean value that controls whether the P:System.Net.CredentialCache....
Definition: WebClient.cs:650
virtual long ContentLength
When overridden in a descendant class, gets or sets the content length of the request data being sent...
Definition: WebRequest.cs:265
UploadDataCompletedEventHandler UploadDataCompleted
Occurs when an asynchronous data-upload operation completes.
Definition: WebClient.cs:789
abstract long Seek(long offset, SeekOrigin origin)
When overridden in a derived class, sets the position within the current stream.
virtual bool CanTimeout
Gets a value that determines whether the current stream can time out.
Definition: Stream.cs:597
Task< Stream > OpenReadTaskAsync(string address)
Opens a readable stream containing the specified resource as an asynchronous operation using a task o...
Definition: WebClient.cs:3339
delegate void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.DownloadStringCompleted event of a ...
virtual void OnUploadStringCompleted(UploadStringCompletedEventArgs e)
Raises the E:System.Net.WebClient.UploadStringCompleted event.
Definition: WebClient.cs:2761
Task< TResult > Task
Gets the T:System.Threading.Tasks.Task`1 created by this T:System.Threading.Tasks....
Defines an application's caching requirements for resources obtained by using T:System....
Stream OpenRead(Uri address)
Opens a readable stream for the data downloaded from a resource with the URI specified as a T:System....
Definition: WebClient.cs:1084
byte [] UploadValues(Uri address, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI.
Definition: WebClient.cs:1554
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
virtual ICredentials Credentials
When overridden in a descendant class, gets or sets the network credentials used for authenticating t...
Definition: WebRequest.cs:299
static readonly string UriSchemeFile
Specifies that the URI is a pointer to a file. This field is read-only.
Definition: Uri.cs:145
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
virtual void OnUploadProgressChanged(UploadProgressChangedEventArgs e)
Raises the E:System.Net.WebClient.UploadProgressChanged event.
Definition: WebClient.cs:3880
string UploadString(string address, string data)
Uploads the specified string to the specified resource, using the POST method.
Definition: WebClient.cs:1643
virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
Begins an asynchronous write operation. (Consider using M:System.IO.Stream.WriteAsync(System....
Definition: Stream.cs:1086
ICredentials Credentials
Gets or sets the network credentials that are sent to the host and used to authenticate the request.
Definition: WebClient.cs:635
virtual void OnWriteStreamClosed(WriteStreamClosedEventArgs e)
Raises the E:System.Net.WebClient.WriteStreamClosed event.
Definition: WebClient.cs:859
WebExceptionStatus
Defines status codes for the T:System.Net.WebException class.
OpenWriteCompletedEventHandler OpenWriteCompleted
Occurs when an asynchronous operation to open a stream to write data to a resource completes.
Definition: WebClient.cs:774
bool IsBusy
Gets whether a Web request is in progress.
Definition: WebClient.cs:755
The exception that is thrown when one of the arguments provided to a method is not valid.
abstract long Length
When overridden in a derived class, gets the length in bytes of the stream.
Definition: Stream.cs:621
virtual void Abort()
Aborts the Request
Definition: WebRequest.cs:854
Task< byte[]> UploadFileTaskAsync(Uri address, string method, string fileName)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
Definition: WebClient.cs:3743
virtual void OnDownloadFileCompleted(AsyncCompletedEventArgs e)
Raises the E:System.Net.WebClient.DownloadFileCompleted event.
Definition: WebClient.cs:2676
byte [] UploadValues(Uri address, string method, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI,...
Definition: WebClient.cs:1584
virtual long ContentLength
When overridden in a descendant class, gets or sets the content length of data being received.
Definition: WebResponse.cs:49
virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs e)
Raises the E:System.Net.WebClient.UploadDataCompleted event.
Definition: WebClient.cs:2917
WebHeaderCollection ResponseHeaders
Gets a collection of header name/value pairs associated with the response.
Definition: WebClient.cs:704
void UploadValuesAsync(Uri address, string method, NameValueCollection data)
Uploads the data in the specified name/value collection to the resource identified by the specified U...
Definition: WebClient.cs:3214
string DownloadString(Uri address)
Downloads the requested resource as a T:System.String. The resource to download is specified as a T:S...
Definition: WebClient.cs:1746
virtual byte [] GetPreamble()
When overridden in a derived class, returns a sequence of bytes that specifies the encoding used.
Definition: Encoding.cs:1453
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
void Post(SendOrPostCallback d, object arg)
Invokes a delegate on the thread or context appropriate for the application model.
static AsyncOperation CreateOperation(object userSuppliedState)
Returns an T:System.ComponentModel.AsyncOperation for tracking the duration of a particular asynchron...
Creates or manipulates threads other than its own, which might be harmful to the host.
object UserSuppliedState
Gets or sets an object used to uniquely identify an asynchronous operation.
OpenReadCompletedEventHandler OpenReadCompleted
Occurs when an asynchronous operation to open a stream containing a resource completes.
Definition: WebClient.cs:771
byte [] UploadData(string address, string method, byte[] data)
Uploads a data buffer to the specified resource, using the specified method.
Definition: WebClient.cs:1254
delegate void OpenReadCompletedEventHandler(object sender, OpenReadCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.OpenReadCompleted event of a T:Syst...
delegate void UploadFileCompletedEventHandler(object sender, UploadFileCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.UploadFileCompleted event of a T:Sy...
Provides data for the E:System.Net.WebClient.DownloadDataCompleted event.
byte [] Result
Gets the data that is downloaded by a Overload:System.Net.WebClient.DownloadDataAsync method.
void PostOperationCompleted(SendOrPostCallback d, object arg)
Ends the lifetime of an asynchronous operation.
abstract long Position
When overridden in a derived class, gets or sets the position within the current stream.
Definition: Stream.cs:633
virtual IWebProxy Proxy
When overridden in a descendant class, gets or sets the network proxy to use to access this Internet ...
Definition: WebRequest.cs:337
Provides data for the E:System.Net.WebClient.UploadFileCompleted event.
virtual int Count
Gets the number of key/value pairs contained in the T:System.Collections.Specialized....
virtual void OnUploadFileCompleted(UploadFileCompletedEventArgs e)
Raises the E:System.Net.WebClient.UploadFileCompleted event.
Definition: WebClient.cs:3037
string DownloadString(string address)
Downloads the requested resource as a T:System.String. The resource to download is specified as a T:S...
Definition: WebClient.cs:1731
static Encoding UTF8
Gets an encoding for the UTF-8 format.
Definition: Encoding.cs:1023
void OpenWriteAsync(Uri address, string method, object userToken)
Opens a stream for writing data to the specified resource, using the specified method....
Definition: WebClient.cs:2468
Stream OpenWrite(string address, string method)
Opens a stream for writing data to the specified resource, using the specified method.
Definition: WebClient.cs:1156
void OpenReadAsync(Uri address)
Opens a readable stream containing the specified resource. This method does not block the calling thr...
Definition: WebClient.cs:2352
Provides static methods for the creation, copying, deletion, moving, and opening of a single file,...
Definition: File.cs:14
Manipulates arrays of primitive types.
Definition: Buffer.cs:11
bool AllowReadStreamBuffering
Gets or sets a value that indicates whether to buffer the data read from the Internet resource for a ...
Definition: WebClient.cs:564
byte [] UploadValues(string address, string method, NameValueCollection data)
Uploads the specified name/value collection to the resource identified by the specified URI,...
Definition: WebClient.cs:1567
Task< byte[]> UploadDataTaskAsync(Uri address, string method, byte[] data)
Uploads a data buffer that contains a T:System.Byte array to the URI specified as an asynchronous ope...
Definition: WebClient.cs:3666
static void Delete(string path)
Deletes the specified file.
Definition: File.cs:324
Provides data for the E:System.Net.WebClient.WriteStreamClosed event.
Provides the base interface for implementation of proxy access for the T:System.Net....
Definition: IWebProxy.cs:5
void DownloadStringAsync(Uri address, object userToken)
Downloads the specified string to the specified resource. This method does not block the calling thre...
Definition: WebClient.cs:2564
Provides data for the E:System.Net.WebClient.DownloadProgressChanged event of a T:System....
virtual int EndRead(IAsyncResult asyncResult)
Waits for the pending asynchronous read to complete. (Consider using M:System.IO.Stream....
Definition: Stream.cs:982
virtual WebResponse GetResponse()
When overridden in a descendant class, returns a response to an Internet request.
Definition: WebRequest.cs:725
Task< byte[]> UploadDataTaskAsync(string address, byte[] data)
Uploads a data buffer that contains a T:System.Byte array to the URI specified as an asynchronous ope...
Definition: WebClient.cs:3625
static int Decrement(ref int location)
Decrements a specified variable and stores the result, as an atomic operation.
Definition: Interlocked.cs:40
Provides constants and static methods for trigonometric, logarithmic, and other common mathematical f...
Definition: Math.cs:10
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
byte [] DownloadData(Uri address)
Downloads the resource as a T:System.Byte array from the URI specified.
Definition: WebClient.cs:929
void CancelAsync()
Cancels a pending asynchronous operation.
Definition: WebClient.cs:3282
delegate void UploadValuesCompletedEventHandler(object sender, UploadValuesCompletedEventArgs e)
Represents the method that will handle the E:System.Net.WebClient.UploadValuesCompleted event of a T:...
Task< byte[]> DownloadDataTaskAsync(string address)
Downloads the resource as a T:System.Byte array from the URI specified as an asynchronous operation u...
Definition: WebClient.cs:3534
The exception that is thrown when a call is made to the M:System.Threading.Thread....
Provides an object representation of a uniform resource identifier (URI) and easy access to the parts...
Definition: Uri.cs:19
IWebProxy Proxy
Gets or sets the proxy used by this T:System.Net.WebClient object.
Definition: WebClient.cs:720
virtual Stream GetResponseStream()
When overridden in a descendant class, returns the data stream from the Internet resource.
Definition: WebResponse.cs:184
Provides data for the E:System.Net.WebClient.DownloadStringCompleted event.
delegate void AsyncCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
Represents the method that will handle the MethodNameCompleted event of an asynchronous operation.
byte [] UploadData(Uri address, byte[] data)
Uploads a data buffer to a resource identified by a URI.
Definition: WebClient.cs:1241
Provides data for the E:System.Net.WebClient.UploadProgressChanged event of a T:System....
Task< byte[]> DownloadDataTaskAsync(Uri address)
Downloads the resource as a T:System.Byte array from the URI specified as an asynchronous operation u...
Definition: WebClient.cs:3546
Provides an T:System.IProgress`1 that invokes callbacks for each reported progress value.
Definition: Progress.cs:8
virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
When overridden in a descendant class, returns a T:System.Net.WebResponse.
Definition: WebRequest.cs:747
Provides atomic operations for variables that are shared by multiple threads.
Definition: Interlocked.cs:10
override string ToString()
Gets a canonical string representation for the specified T:System.Uri instance.
Definition: Uri.cs:1663
The exception that is thrown when a security error is detected.
DownloadDataCompletedEventHandler DownloadDataCompleted
Occurs when an asynchronous data download operation completes.
Definition: WebClient.cs:780
Performs operations on T:System.String instances that contain file or directory path information....
Definition: Path.cs:13
byte [] Result
Gets the server reply to a data upload operation that is started by calling an Overload:System....
virtual void EndWrite(IAsyncResult asyncResult)
Ends an asynchronous write operation. (Consider using M:System.IO.Stream.WriteAsync(System....
Definition: Stream.cs:1162
static NumberFormatInfo InvariantInfo
Gets a read-only T:System.Globalization.NumberFormatInfo object that is culture-independent (invarian...
Provides data for the E:System.Net.WebClient.UploadValuesCompleted event.
Task< string > UploadStringTaskAsync(string address, string data)
Uploads the specified string to the specified resource as an asynchronous operation using a task obje...
Definition: WebClient.cs:3454
void UploadDataAsync(Uri address, string method, byte[] data, object userToken)
Uploads a data buffer to a resource identified by a URI, using the specified method and identifying t...
Definition: WebClient.cs:2982
virtual WebHeaderCollection Headers
When overridden in a derived class, gets a collection of header name-value pairs associated with this...
Definition: WebResponse.cs:96
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.
Provides culture-specific information for formatting and parsing numeric values.
Task< byte[]> UploadFileTaskAsync(string address, string method, string fileName)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
Definition: WebClient.cs:3728
Task< byte[]> UploadDataTaskAsync(string address, string method, byte[] data)
Uploads a data buffer that contains a T:System.Byte array to the URI specified as an asynchronous ope...
Definition: WebClient.cs:3652
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16
Task< string > DownloadStringTaskAsync(Uri address)
Downloads the resource as a T:System.String from the URI specified as an asynchronous operation using...
Definition: WebClient.cs:3308