本文整理汇总了C#中System.Net.WebClient.DownloadData方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.DownloadData方法的具体用法?C# WebClient.DownloadData怎么用?C# WebClient.DownloadData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.DownloadData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFileFromSite
/// <summary>
/// method to download the contents of a file from a remote URI
/// </summary>
/// <param name="ftpUri"></param>
/// <param name="user"></param>
/// <param name="pass"></param>
/// <returns></returns>
public static string GetFileFromSite(Uri ftpUri, string user, string pass)
{
string fileString = string.Empty;
// The serverUri parameter should start with the ftp:// scheme.
if (ftpUri.Scheme != Uri.UriSchemeFtp)
{
return string.Empty;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
NetworkCredential nc = new NetworkCredential(user, pass);
CredentialCache cc = new CredentialCache();
cc.Add(ftpUri, "Basic", nc);
request.Credentials = cc;
try
{
byte[] newFileData = request.DownloadData(ftpUri.ToString());
fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
m_logger.WriteToLogFile("FtpUtils::GetFileFromSite();ECaught: " + e.Message);
}
return fileString;
}
示例2: GetConvertion
public decimal GetConvertion(string from, string to)
{
WebClient objWebClient = null;
UTF8Encoding objUTF8 = null;
decimal result = 0;
try{
objWebClient = new WebClient();
objUTF8 = new UTF8Encoding();
byte[] aRequestedHTML = objWebClient.DownloadData(String.Format("http://www.xe.com/ucc/convert/?Amount=1&From={0}&To={1}", from, to));
string strRequestedHTML = objUTF8.GetString(aRequestedHTML);
int search1 = strRequestedHTML.LastIndexOf(" <span class=\"uccResCde\">USD</span>");
string search2 = strRequestedHTML.Substring(search1 - 21, 21);
int search3 = search2.LastIndexOf(">");
string stringRepresentingCE = search2.Substring(search3 + 1);
result = Convert.ToDecimal(stringRepresentingCE.Trim());
}
catch (Exception ex){
// Agregar codigo para manejar la excepción.
}
return result;
}
示例3: GetAvatar
public ActionResult GetAvatar(int size)
{
string uid = Session["currentUserId"].ToString();
AccountModel user = null;
byte[] avatar = null;
using (var db = new AppContext())
{
user = db.Accounts.Where(a => a.WeiboId == uid).ToList().First();
}
using (var client = new WebClient())
{
switch (size)
{
case 50:
avatar = client.DownloadData(user.Avatar50Url);
break;
case 180:
default:
avatar = client.DownloadData(user.Avatar180Url);
break;
}
}
return File(avatar, "image/jpeg");
}
示例4: Main
static void Main(string[] args)
{
var wc = new WebClient();
wc.UploadFile("http://localhost:1729/api/Bib2/UploadFile", "POST", @"C:\rest\Nowy dokument tekstowy.txt");
Console.WriteLine("Upload done");
DownloadFileAsync(@"C:\rest1\encypt", "encrypt").Wait();
Console.WriteLine("Encrypt done");
DownloadFileAsync(@"C:\rest1\decrypt.txt", "decrypt").Wait();
Console.WriteLine("Decrypt done");
Console.WriteLine("MD5 SUM:");
byte[] md5 = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=MD5");
foreach (var item in md5)
{
Console.WriteLine(item);
}
Console.WriteLine("SHA SUM");
byte[] sha = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=SHA");
foreach (var item in sha)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
示例5: GetUpdateInfo
private static bool GetUpdateInfo(out UpdateInfo info)
{
const string keyLink = "link =";
const string keyVersion = "version =";
info = default(UpdateInfo);
using (var client = new WebClient())
{
try
{
var data = client.DownloadData(UpdateUrl + "index.txt");
var updIndex = Encoding.Default.GetString(data).Split('\n');
var updInfo = new StringBuilder();
for (var i = 0; i < updIndex.Length; i++)
{
var buf = updIndex[i].Trim();
var version = new Version(buf);
if (version <= Root.Version)
continue;
info.IsNewer = true;
for (var j = i; j < updIndex.Length; j++)
{
data = client.DownloadData(UpdateUrl + updIndex[j].Trim() + ".txt");
var lines = Encoding.Default.GetString(data).Split('\n');
for (var k = 0; k < lines.Length; k++)
{
updInfo.Append(lines[k]);
updInfo.Append("\r\n");
}
updInfo.Append("\r\n\r\n");
}
break;
}
if (updInfo.Length == 0)
return true;
info.Description = updInfo.ToString();
data = client.DownloadData(UpdateUrl + "latest.txt");
updIndex = Encoding.Default.GetString(data).Split('\n');
for (var i = 0; i < updIndex.Length; i++)
{
if (updIndex[i].StartsWith(keyLink))
{
info.Link = updIndex[i].Substring(keyLink.Length).Trim();
continue;
}
if (updIndex[i].StartsWith(keyVersion))
{
info.Version = updIndex[i].Substring(keyVersion.Length).Trim();
break;
}
}
return true;
}
catch (Exception)
{
//Log("! Update attempt failed: " + e.Message);
return false;
}
}
}
示例6: TestFixtureSetUp
public void TestFixtureSetUp()
{
using (var c = new WebClient())
{
_examples[true] = c.DownloadData(ValidXhtmlUrl);
_examples[false] = c.DownloadData(InvalidXhtmlUrl);
}
}
示例7: button1_Click
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0 || !(textBox1.Text.ToLowerInvariant().StartsWith("http://www.youtube.com/watch?v=") || textBox1.Text.ToLowerInvariant().StartsWith("www.youtube.com/watch?v=") || textBox1.Text.ToLowerInvariant().StartsWith("youtube.com/watch?v=")))
{
MessageBox.Show("Please enter a valid YouTube URL!");
return;
}
richTextBox1.Clear();
richTextBox1.Text = "Retrieving...";
richTextBox1.Refresh();
if (textBox1.Text.ToLowerInvariant().StartsWith("youtube.com/watch?v="))
textBox1.Text = "http://www." + textBox1.Text;
if (textBox1.Text.ToLowerInvariant().StartsWith("www.youtube.com/watch?v="))
textBox1.Text = "http://" + textBox1.Text;
try
{
WebClient wc = new WebClient();
byte[] response = wc.DownloadData(textBox1.Text);
string content = Encoding.ASCII.GetString(response);
content = content.Substring(content.IndexOf("<p id=\"watch-uploader-info\">") + 28);
int start = content.IndexOf("<") + 9;
int stop;
content = content.Substring(start);
if (!content.StartsWith(@"/user/"))
{
content = content.Substring(content.IndexOf("<") + 1);
content = content.Substring(content.IndexOf("<"));
start = content.IndexOf("<") + 9;
stop = content.IndexOf("class", start) - 2;
content = content.Substring(start, stop - start);
}
else
{
stop = content.IndexOf("class") - 2;
content = content.Substring(0, stop);
}
string channel = "http://youtube.com" + content;
string line1 = "Uploader Channel: " + channel;
response = wc.DownloadData(channel);
content = Encoding.ASCII.GetString(response);
content = content.Substring(content.IndexOf("<span class=\"stat-value\">") + 25);
string line2 = "\r\nSubscribers: " + content.Substring(0, content.IndexOf("<"));
content = content.Substring(content.IndexOf("<span class=\"stat-value\">") + 25);
string line3 = "\r\nVideo views: " + content.Substring(0, content.IndexOf("<"));
richTextBox1.Text = line1;
richTextBox1.Text += line2;
richTextBox1.Text += line3;
richTextBox1.Refresh();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
}
示例8: ProcessRequest
public void ProcessRequest(HttpContext context)
{
Logger logger = LogManager.GetCurrentClassLogger();
try
{
WebClient webClient = new WebClient();
string login = "", pass = "";
login = ConfigurationManager.AppSettings["loginForService"];
pass = ConfigurationManager.AppSettings["passwordForService"];
webClient.Credentials = new NetworkCredential(login, pass);
byte[] arrMain;
byte[] arrMicro;
byte[] arrExtraAttachment;
if ((context.Session["SilabMainResultUri"] != null) && (context.Request.Form["Main"] != null || context.Request.QueryString["Main"] != null))
{
arrMain = webClient.DownloadData(context.Session["SilabMainResultUri"].ToString());
context.Response.Clear();
context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoResults" + context.Session["barcode"] + ".pdf");
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(arrMain);
context.Response.Flush();
}
if ((context.Session["SilabMicroResultUri"] != null) && (context.Request.Form["Micro"] != null || context.Request.QueryString["Micro"] !=null))
{
arrMicro = webClient.DownloadData(context.Session["SilabMicroResultUri"].ToString());
context.Response.Clear();
context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoResults" + context.Session["barcode"] + "_Micro.pdf");
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(arrMicro);
context.Response.Flush();
}
if ((context.Session["ExtraAttachmentUri"] != null) && (context.Request.Form["ExtraAttachment"] != null || context.Request.QueryString["ExtraAttachment"] != null))
{
ArrayList arrExtraAttachment_ = (ArrayList)context.Session["ExtraAttachmentUri"];
arrExtraAttachment = webClient.DownloadData(arrExtraAttachment_[0].ToString());
context.Response.Clear();
context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoAddResults" + context.Session["barcode"] + "_Add.pdf");
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(arrExtraAttachment);
context.Response.Flush();
}
}
catch (System.Threading.ThreadAbortException ex)
{
logger.Warn(ex.Message + " | Row: " + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
}
catch (Exception ex)
{
logger.Warn(ex.Message + " | Row: " + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
}
}
示例9: Main
static void Main(string[] args)
{
try
{
// Get url.
string url = "http://edu.regi.rovno.ua/";
// Report url.
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("... PageTimeTest: times web pages");
Console.ResetColor();
Console.WriteLine("Testing: {0}", url);
// Fetch page.
using (System.Net.WebClient client = new System.Net.WebClient())
{
// Set gzip.
client.Headers["Accept-Encoding"] = "gzip";
// Download.
// ... Do an initial run to prime the cache.
byte[] data = client.DownloadData(url);
// Start timing.
Stopwatch stopwatch = Stopwatch.StartNew();
// Iterate.
for (int i = 0; i < Math.Min(100, _max); i++)
{
data = client.DownloadData(url);
}
// Stop timing.
stopwatch.Stop();
// Report times.
Console.WriteLine("Time required: {0} ms",
stopwatch.Elapsed.TotalMilliseconds); //повний час загрузки
Console.WriteLine("Time per page: {0} ms",
stopwatch.Elapsed.TotalMilliseconds / _max); //середній час загрузки
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.WriteLine("[Done]");
Console.ReadLine();
}
}
示例10: Load
public System.IO.Stream Load(object source)
{
var webClient = new WebClient();
byte[] html = null;
if (source is string)
html = webClient.DownloadData(source as string);
else if (source is Uri)
html = webClient.DownloadData(source as Uri);
if (html == null || html.Count() == 0) return null;
return new MemoryStream(html);
}
示例11: BeginLoadImageFromSearch
public static void BeginLoadImageFromSearch(string search, bool isRandom = true)
{
_currentSearch = search;
ThreadPool.QueueUserWorkItem((s)=>
{
try
{
//load google images page
var url = new Uri(string.Format(_urlScheme, Uri.EscapeDataString(search)));
var wc = new WebClient();
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
var str = wc.DownloadString(url);
//declarations
byte[] imgData = null;
int index1 = 0, index2 = 0;
//find first url
index1 = str.IndexOf(_parse1) + _parse1.Length;
//if random - skip some urls
if (isRandom)
{
var randomNumber = rand.Next(0, 5);
for (int i = 0; i < randomNumber; i++)
index1 = str.IndexOf(_parse1, index1) + _parse1.Length;
}
//find url end
index2 = str.IndexOf(_parse2, index1);
//download url
try
{
imgData = wc.DownloadData(new Uri(str.Substring(index1, index2 - index1)));
}
catch
{
//if download failed - try next url once
index1 = str.IndexOf(_parse1, index1) + _parse1.Length;
index2 = str.IndexOf(_parse2, index1);
imgData = wc.DownloadData(new Uri(str.Substring(index1, index2 - index1)));
}
//bytes to image
var image = ImageLoader.LoadImage(new MemoryStream(imgData));
//run event
if (_currentSearch == search && ImageLoaded != null)
ImageLoaded(null, image);
}
catch { if (ImageLoadFail != null) ImageLoadFail(null, null); }
});
}
示例12: button1_Click
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text=="")
{
MessageBox.Show("请填写单词,不要为空!谢谢!","提示");
}
else
{
richTextBox1.Clear();
WebClient we = new WebClient();
byte[] myDataBuffer;
we.Headers.Add("user-agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
try
{
myDataBuffer = we.DownloadData("https://translate.google.com.hk/translate_a/t?client=t&sl=en&tl=zh-CN&hl=zh-CN&sc=2&ie=UTF-8&oe=UTF-8&prev=enter&ssel=0&tsel=0&q=" + textBox1.Text);
}
catch (WebException ex)
{
//MessageBox.Show("服务器异常,请检查网络!","Error");
MessageBox.Show(ex.Message);
throw;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
string download = Encoding.UTF8.GetString(myDataBuffer);
richTextBox1.AppendText(download);
}
}
示例13: GetImage
public byte[] GetImage(string url)
{
using (var client = new WebClient())
{
return client.DownloadData(url);
}
}
示例14: RemoveTorrent
public static void RemoveTorrent(string address, string username, string password, string hash)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(username, password);
string fullAddress = "http://" + address + "/gui/?action=remove&hash=" + hash;
wc.DownloadData(fullAddress);
}
示例15: GetData
static string GetData(Uri uri)
{
var wc = new WebClient();
wc.Proxy = null;
var data = wc.DownloadData(uri);
return Encoding.UTF8.GetString(data);
}