Using WebClient

From PeformIQ Upgrade
Jump to navigation Jump to search

See - http://stackoverflow.com/questions/6348804/net-error-when-calling-system-net-webclient-uploadfileasync

var targetUri = new Uri("ftp://example.com/file.txt");
var srcFile = string.Empty;  // documentation says this will throw WebException
var client = new WebClient();
client.UploadFileAsync(targetUri, "STOR", srcFile, null);

XtremeDotNetTalk

From - http://www.xtremedotnettalk.com/showthread.php?t=95893

string url = "http://localhost/images/test.jpg"

// Download the file
// (using System.Net)
WebClient client = new WebClient();
client.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] data = client.DownloadData(url);

// write the file to the temp directory
// (using System.IO)
string path = Path.GetTempPath() + @"\image.jpg";
FileStream fileStream = new FileStream(path, FileMode.Create);
fileStream.Write(data, 0, data.Length);
fileStream.Close();

// open the file
// (using System.Diagnostics)
Process process = new Process();
process.StartInfo.FileName = path;
process.Start();

eggheadcafe

From - http://www.eggheadcafe.com/community/csharp/2/10038606/webclient-throwing-exception.aspx

private void button1_Click(object sender, EventArgs e)

{

   this.label1.Text = "btn1 clicked";

   WebClient Client = new WebClient();
   try
      {

         WebProxy proxyObject = new WebProxy("http://corporate.proxy.com:8888/", true);
         Client.Proxy = proxyObject;

         string userName = "myDomain\\myUserName";
         string password = "mypassword";

         Client.Credentials = new NetworkCredential(userName, password);

         Client.DownloadFile("http://www.gutenberg.org/files/25662/25662.txt", "c:\\temp\\myTestFile.txt");
      }

      catch (WebException ex)
      {
         MessageBox.Show(ex.ToString());
      }

      catch (Exception ex)
      {
         MessageBox.Show(ex.ToString());
      }
}