本文整理汇总了C#中System.Net.WebClient类的典型用法代码示例。如果您正苦于以下问题:C# System.Net.WebClient类的具体用法?C# System.Net.WebClient怎么用?C# System.Net.WebClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
System.Net.WebClient类属于命名空间,在下文中一共展示了System.Net.WebClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Initialize
public override void Initialize()
{
string path = Path.Combine(TShock.SavePath, "CodeReward1_9.json");
Config = Config.Read(path);
if (!File.Exists(path))
{
Config.Write(path);
}
Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "codereward"));
Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "crt"));
Variables.ALL = Config.ALL;
//Events
ServerApi.Hooks.ServerChat.Register(this, Chat.onChat);
string version = "1.3.0.8 (1.9)";
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://textuploader.com/al9u6/raw");
if (version != webData)
{
Console.WriteLine("[CodeReward] New version is available!: " + webData);
}
System.Timers.Timer timer = new System.Timers.Timer(Variables.ALL.Interval * (60 * 1000));
timer.Elapsed += run;
timer.Start();
}
示例2: btnSend_Click
private void btnSend_Click(object sender, EventArgs e)
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
try
{
string url = "http://smsc.vianett.no/v3/send.ashx?" +
"src=" + textPhoneNumber.Text + "&" +
"dst=" + textPhoneNumber.Text + "&" +
"msg=" +
System.Web.HttpUtility.UrlEncode(textMessage.Text,
System.Text.Encoding.GetEncoding("ISO-8859-1")) + "&" +
"username=" + System.Web.HttpUtility.UrlEncode(textUserName.Text) + "&" +
"password=" + System.Web.HttpUtility.UrlEncode(textPassword.Text);
string result = client.DownloadString(url);
if (result.Contains("OK"))
MessageBox.Show("Your message has been successfully sent.", "Message", MessageBoxButtons.OK,
MessageBoxIcon.Information);
else
MessageBox.Show("Your message was not successfully delivered", "Message", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
示例3: GetUUIDButton_Click
private void GetUUIDButton_Click(object sender, EventArgs e)
{
//If the user does NOT have an internet connection then display a message, otherwise, continue!
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
{
MessageBox.Show("Connection failed, make sure you are connected to the internet!");
}
else
{
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("https://api.mojang.com/users/profiles/minecraft/" + UsernameBox.Text);
//If the webpage does not load or has no strings then say the username was invalid! Otherwise, continue!
if (webData == "")
{
MessageBox.Show("Your username is invalid, please check and retry!");
}
else
{
string[] mojangAPI = webData.Split(new Char[] { ',', ' ' });
mojangAPI[0] = mojangAPI[0].Substring(7);
mojangAPI[0] = mojangAPI[0].Remove((mojangAPI[0].Length - 1), 1);
UUIDBox.Text = mojangAPI[0];
}
}
}
示例4: CurrentWeather
public CurrentWeather(string fetched, JObject json)
{
Fetched = fetched;
Json = json;
if (Json["current_observation"]["temp_f"] != null)
{
CurrentTempF = (double)Json["current_observation"]["temp_f"];
FeelsLikeF = (double)Json["current_observation"]["feelslike_f"];
CurrentTempC = (double)Json["current_observation"]["temp_c"];
FeelsLikeC = (double)Json["current_observation"]["feelslike_c"];
CityName = (string)Json["current_observation"]["display_location"]["full"];
WindFeel = (string)Json["current_observation"]["wind_string"];
WindSpeedMph = (double)Json["current_observation"]["wind_mph"];
DewPointF = (double)Json["current_observation"]["dewpoint_f"];
ForecastURL = (string)Json["current_observation"]["forecast_url"];
VisibilityMi = (double)Json["current_observation"]["visibility_mi"];
Weather = (string)Json["current_observation"]["weather"];
Elevation = (string)Json["current_observation"]["observation_location"]["elevation"];
ImageName = (string)Json["current_observation"]["icon"];
ImageUrl = (string)Json["current_observation"]["icon_url"];
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
LocalUrl = System.IO.Path.Combine(folder, System.IO.Path.GetRandomFileName());
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(ImageUrl, LocalUrl);
}
}
示例5: Retreive
public string Retreive(string Url)
{
System.Net.WebClient _WebClient = new System.Net.WebClient();
string _Result = _WebClient.DownloadString(Url);
return _Result;
}
示例6: MainWindow
public MainWindow()
{
InitializeComponent();
// 以下を追加
this.btnDownload.Click += (sender, e) =>
{
var client = new System.Net.WebClient();
byte[] buffer = client.DownloadData("http://k-db.com/?p=all&download=csv");
string str = Encoding.Default.GetString(buffer);
string[] rows = str.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
// 1行目をラベルに表示
this.lblTitle.Content = rows[0];
// 2行目以下はカンマ区切りから文字列の配列に変換しておく
List<string[]> list = new List<string[]>();
rows.ToList().ForEach(row => list.Add(row.Split(new char[] { ',' })));
// ヘッダの作成(データバインド用の設計)
GridView view = new GridView();
list.First().Select((item, cnt) => new { Count = cnt, Item = item }).ToList().ForEach(header =>
{
view.Columns.Add(
new GridViewColumn()
{
Header = header.Item,
DisplayMemberBinding = new Binding(string.Format("[{0}]", header.Count))
});
});
// これらをリストビューに設定
lvStockList.View = view;
lvStockList.ItemsSource = list.Skip(1);
};
}
示例7: DownloadString
private static string DownloadString(string uri)
{
Thread.Sleep(5000);
using (var wc = new System.Net.WebClient())
return wc.DownloadString(uri);
}
示例8: Main
static void Main(string[] args)
{
//Inkorrekte Argumente
if (args.Length != 1)
{
//Falsche Anzahl der Argumente
Console.WriteLine("Benutzung: dhltrack [Delivery-ID]");
}
else
{
//The joy of working with modern languages...
string id = args[0]; //Building up the URL...
string url = "http://nolp.dhl.de/nextt-online-public/set_identcodes.do?lang=de&idc=" + id;
System.Net.WebClient wc = new System.Net.WebClient();
wc.Encoding = UTF8Encoding.UTF8;
string htmldata = wc.DownloadString(url);
if (htmldata.Contains("<div class=\"error\">")) //DHL gibt bei nicht vorhandener ID den Error in dieser CSS-Klasse heraus.
{
//Leider nicht vorhanden.
Console.WriteLine("Es ist keine Sendung mit der ID " + id + " bekannt!");
}
else
{
//Status der Sendung extrahieren -- evtl. wäre hier ein RegExp besser...
string status = htmldata.Split(new[] { "<td class=\"status\">" }, StringSplitOptions.None)[1].Split(new[] { "</td>" }, StringSplitOptions.None)[0].Replace("<div class=\"statusZugestellt\">", "").Replace("</div>", "").Trim();
Console.WriteLine("Status der Sendung mit ID: " + id);
Console.WriteLine(status);
}
}
}
示例9: GetPlayerGames
public SteamPlayerGames GetPlayerGames(string profileName)
{
var client = new System.Net.WebClient();
string xml = client.DownloadString(string.Format(getPlayerGamesUrl, profileName));
return SteamPlayerGames.Deserialize(xml);
}
示例10: GetWebServiceAssembly
/// <summary>
/// get an Assembly according to wsdl path.
/// </summary>
/// <param name="wsdl">wsdl path</param>
/// <param name="nameSpace">namespace</param>
/// <returns>return Assembly</returns>
public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace)
{
try
{
System.Net.WebClient webClient = new System.Net.WebClient();
System.IO.Stream webStream = webClient.OpenRead(wsdl);
ServiceDescription serviceDescription = ServiceDescription.Read(webStream);
ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter();
serviceDescroptImporter.AddServiceDescription(serviceDescription, "", "");
System.CodeDom.CodeNamespace codeNameSpace = new System.CodeDom.CodeNamespace(nameSpace);
System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit();
codeCompileUnit.Namespaces.Add(codeNameSpace);
serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit);
System.CodeDom.Compiler.CodeDomProvider codeDom = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters();
codeParameters.GenerateExecutable = false;
codeParameters.GenerateInMemory = true;
codeParameters.ReferencedAssemblies.Add("System.dll");
codeParameters.ReferencedAssemblies.Add("System.XML.dll");
codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
codeParameters.ReferencedAssemblies.Add("System.Data.dll");
System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit);
return compilerResults.CompiledAssembly;
}
catch (Exception ex)
{
throw ex;
}
}
示例11: Get
public static string Get(string msg)
{
try {
var url = "http://www.aphorismen.de/suche?text=" + Uri.EscapeDataString (msg) + "&autor_quelle=&thema=";
var webClient = new System.Net.WebClient ();
var s = webClient.DownloadString (url);
var doc = new HtmlDocument ();
doc.LoadHtml (s);
var toftitle = doc.DocumentNode.Descendants ().Where
(x => (x.Name == "p" && x.Attributes ["class"] != null &&
x.Attributes ["class"].Value.Contains ("spruch text"))).ToList ();
if (toftitle.Count > 0) {
var seed = Convert.ToInt32 (Regex.Match (Guid.NewGuid ().ToString (), @"\d+").Value);
var i = new Random (seed).Next (0, toftitle.Count);
return toftitle [i].InnerText;
}
} catch {
return null;
}
return null;
}
示例12: GetStringFromURL
internal string GetStringFromURL(string URL)
{
string cacheKey = string.Format("GetStringFromURL_{0}", URL);
var cached = CacheProvider.Get<string>(cacheKey);
if (cached != null)
{
LogProvider.LogMessage("Url.GetStringFromURL : Returning cached result");
return cached;
}
LogProvider.LogMessage("Url.GetStringFromURL : Cached result unavailable, fetching url content");
string result;
try
{
result = new System.Net.WebClient().DownloadString(URL);
}
catch (Exception error)
{
if (LogProvider.HandleAndReturnIfToThrowError(error))
throw;
return null;
}
CacheProvider.Set(result, cacheKey);
return result;
}
示例13: GetSSQResult
/// <summary>
/// 获取双色球开奖结果
/// </summary>
/// <returns></returns>
private void GetSSQResult()
{
string ssqResult = "";
try
{
System.Threading.Thread.Sleep(3000);
string html = new System.Net.WebClient().DownloadString("http://www.zhcw.com/kaijiang/index_kj.html");
html = html.Substring(html.IndexOf("<dd>"), html.IndexOf("</dd>") - html.IndexOf("<dd>") + 4).Replace("\r\n","");
string regStr = "<li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiublud\">(.*?)</li>";
var regex = new System.Text.RegularExpressions.Regex(regStr);
System.Text.RegularExpressions.Match m;
if ((m = regex.Match(html)).Success && m.Groups.Count == 8)
{
for (int i = 1; i < 8; i++)
{
ssqResult += "," + m.Groups[i].Value;
}
ssqResult = ssqResult.Substring(1);
}
}
catch (Exception ex)
{
ssqResult = ex.Message;
}
Response.Write(ssqResult);
Response.Flush();
Response.End();
}
示例14: EncryptionButtonInValidateCard_Click
protected void EncryptionButtonInValidateCard_Click(object sender, EventArgs e)
{
Uri baseUri = new Uri("http://webstrar49.fulton.asu.edu/page3/Service1.svc");
UriTemplate myTemplate = new UriTemplate("encrypt?plainText={plainText}");
String plainText = PlainText_TextBox1.Text;
Uri completeUri = myTemplate.BindByPosition(baseUri, plainText);
System.Net.WebClient webClient = new System.Net.WebClient();
byte[] content = webClient.DownloadData(completeUri);
//EncryptionService.Service1Client encryptionClient = new EncryptionService.Service1Client();
// String cipher=encryptionClient.encrypt(plainText);
String contentinString = Encoding.UTF8.GetString(content, 0, content.Length);
String pattern = @"(?<=\>)(.*?)(?=\<)";
Regex r = new Regex(pattern);
Match m = r.Match(contentinString);
String cipher = "";
if (m.Success)
{
cipher = m.Groups[1].ToString();
}
cipherTextBox.Enabled = true;
cipherTextBox.Text = cipher;
cipherTextBox.Enabled = false;
}
示例15: UpdateFileCached
public static bool UpdateFileCached(string remoteUrl, string localUrl, int thresholdInHours = -1)
{
bool returnValue = false;
DateTime threshold;
if (thresholdInHours > -1)
{
threshold = DateTime.Now.AddHours(-thresholdInHours);
}
else
{
threshold = DateTime.MinValue;
}
try
{
if (!File.Exists(localUrl) || File.GetLastWriteTime(localUrl) < threshold)
{
Console.WriteLine("we need to re-download " + localUrl);
using (System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.DownloadFile(remoteUrl, localUrl);
returnValue = true;
}
}
else
{
returnValue = true;
}
}
catch(Exception e)
{
Debug.WriteLine(e);
returnValue = false;
}
return returnValue;
}