本文整理汇总了C#中System.Net.WebClient.OpenRead方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.OpenRead方法的具体用法?C# WebClient.OpenRead怎么用?C# WebClient.OpenRead使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.OpenRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetChampion
/// <summary>
/// Looks up a champion with the specified id.
/// </summary>
/// <param name="region">The region to check</param>
/// <param name="championId">id of the champion to look up</param>
/// <remarks>Version 1.2</remarks>
/// <returns></returns>
public Champion GetChampion(int championId)
{
Champion championCall = new Champion();
Champion staticChampionCall = new Champion();
DataContractJsonSerializer jSerializer = new DataContractJsonSerializer(typeof(Champion));
WebClient webClient = new WebClient();
try
{
championCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(String.Format("https://{0}.api.pvp.net/api/lol/{0}/v1.2/champion/{1}?api_key={2}", _region, championId, _apiKey)));
staticChampionCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(string.Format("https://{0}.api.pvp.net/api/lol/static-data/{0}/v1.2/champion/{1}?champData=all&api_key={2}", _region, championId, _apiKey)));
staticChampionCall.Active = championCall.Active;
staticChampionCall.BotEnabled = championCall.BotEnabled;
staticChampionCall.BotMmEnabled = championCall.BotMmEnabled;
staticChampionCall.FreeToPlay = championCall.FreeToPlay;
staticChampionCall.RankedPlayEnabled = championCall.RankedPlayEnabled;
}
catch (WebException e)
{
throw;
}
return staticChampionCall;
}
示例2: InvokeWebService
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WebServiceProxy.GetWsClassName(url);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider csc = new CSharpCodeProvider();
ICodeCompiler icc = csc.CreateCompiler();
//设定编译参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//编译代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
示例3: Download
public static void Download()
{
using (WebClient wcDownload = new WebClient())
{
try
{
webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
strResponse = wcDownload.OpenRead(optionDownloadURL);
strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None);
int bytesSize = 0;
byte[] downBuffer = new byte[2048];
downloadForm.Refresh();
while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, bytesSize);
PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize);
pBar.Value = PercentProgress;
pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)";
downloadForm.Refresh();
}
}
catch { }
finally
{
webResponse.Close();
strResponse.Close();
strLocal.Close();
extractAndCleanup();
downloadForm.Hide();
}
}
}
示例4: UpdateFiles
public void UpdateFiles()
{
try
{
WriteLine("Local version: " + Start.m_Version);
WebClient wc = new WebClient();
string versionstr;
using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt")))
{
versionstr = sr.ReadLine();
}
Version remoteversion = new Version(versionstr);
WriteLine("Remote version: " + remoteversion);
if(Start.m_Version < remoteversion)
{
foreach(string str in m_Files)
{
WriteLine("Updating: " + str);
wc.DownloadFile(baseurl + str, str);
}
}
wc.Dispose();
WriteLine("Update complete");
}
catch(Exception e)
{
WriteLine("Update failed:");
WriteLine(e);
}
this.Button_Ok.Enabled = true;
}
示例5: TranslateString
/// <summary>
/// Used to perform the actual conversion of the input string
/// </summary>
/// <param name="InputString"></param>
/// <returns></returns>
public override string TranslateString(string InputString)
{
Console.WriteLine("Processing: " + InputString);
string result = "";
using (WebClient client = new WebClient())
{
using (Stream data = client.OpenRead(this.BuildRequestString(InputString)))
{
using (StreamReader reader = new StreamReader(data))
{
string s = reader.ReadToEnd();
result = ExtractTranslatedString(s);
reader.Close();
}
data.Close();
}
}
return result;
}
示例6: LoadXml
/// <summary>
/// loads a xml from the web server
/// </summary>
/// <param name="_url">URL of the XML file</param>
/// <returns>A XmlDocument object of the XML file</returns>
public static XmlDocument LoadXml(string _url)
{
var xmlDoc = new XmlDocument();
try
{
while (Helper.pingForum("forum.mods.de", 10000) == false)
{
Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
System.Threading.Thread.Sleep(15000);
}
xmlDoc.Load(_url);
}
catch (XmlException)
{
while (Helper.pingForum("forum.mods.de", 100000) == false)
{
Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
System.Threading.Thread.Sleep(15000);
}
WebClient client = new WebClient(); ;
Stream stream = client.OpenRead(_url);
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
content = RemoveTroublesomeCharacters(content);
xmlDoc.LoadXml(content);
}
return xmlDoc;
}
示例7: gettict
/// <summary>
/// 获取微信分享signature参数的值
/// </summary>
/// <returns></returns>
private string gettict()
{
WebClient wc = new WebClient();
Stream myStream = wc.OpenRead("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa0e7d758fa3dbcf1&secret=fe230256d7889dc8f6c4c14669599598");
StreamReader sr = new StreamReader(myStream);
String sLine = sr.ReadToEnd();
string access_token = sLine.Split(',')[0].Split(':')[1].Substring(1, sLine.Split(',')[0].Split(':')[1].Length - 2);
wc.Dispose();
string url2 = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
Stream myStream2 = wc.OpenRead(url2);
StreamReader sr2 = new StreamReader(myStream2);
String sLine2 = sr2.ReadToEnd();
string access_token1 = sLine2.Split(',')[2].Split(':')[1].Substring(1, sLine2.Split(',')[2].Split(':')[1].Length - 2);
string string1 = string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url=http://www.zglsjy.com/item/dazhuanpan/index.aspx", access_token1, this.straa.Text, this.timestamp.Text);
this.toke.Text = string1;
// string string2 = "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value";
return SHA1_Hash(string1);
}
示例8: GetApplication
/// <summary>
/// Gets the application with the given name from the server
/// </summary>
/// <param name="app"></param>
public Application GetApplication(string name, string rootUrl)
{
CoreTools.Logger.DebugFormat("Getting online application info for \"{0}\" from {1}", name, rootUrl);
// Make sure that the rootUrl ends with a '/'
if (!rootUrl.EndsWith("/"))
rootUrl += "/";
var application = new Application()
{
Name = name,
Files = new List<string>(),
ApplicationVersion = new Version(),
WebRootUrl = rootUrl
};
// Create a Http client to download data
using (var httpClient = new WebClient())
{
// Open filelist file on the server and store it in the object
var versionRegex = new Regex(@"^[vV][0-9]*\.[0-9]*\.[0-9]*");
var filesContent = new StreamReader(httpClient.OpenRead(string.Format("{0}{1}/files.txt", rootUrl, name)));
while (!filesContent.EndOfStream)
{
var line = filesContent.ReadLine();
// If line matches version format, parse version-number of current version
if (versionRegex.IsMatch(line))
{
var versions = line.Substring(1).Split(new string[] {"."}, StringSplitOptions.RemoveEmptyEntries);
application.ApplicationVersion = new Version(Convert.ToInt32(versions[0]),
Convert.ToInt32(versions[1]),
Convert.ToInt32(versions[2]),
0);
}
else
{
application.Files.Add(line);
}
}
// Get changelog
var changelogReader = new StreamReader(httpClient.OpenRead(string.Format("{0}{1}/changelog.xml", rootUrl, name)));
var xmlContent = changelogReader.ReadToEnd();
application.ChangeLog = System.Xml.Linq.XDocument.Parse(xmlContent);
CoreTools.Logger.DebugFormat("Online application information for \"{0}\" loaded:", name);
CoreTools.Logger.DebugFormat(" - Online version: {0}", application.ApplicationVersion);
return application;
}
}
示例9: FacebookLogin
public ActionResult FacebookLogin(string code, string state, string returnUrl)
{
if (string.IsNullOrEmpty(code))
{
// Redirect to Facebook Login
var redirectUri = this.GetLoginAbsoluteUrl();
var facebookLoginUrl = "https://graph.facebook.com/oauth/authorize?client_id=" + this.facebookApiClientId + "&scope=&state=" + HttpUtility.UrlEncode(returnUrl) + "&redirect_uri=" + HttpUtility.UrlEncode(redirectUri);
return this.Redirect(facebookLoginUrl);
}
var tokenUrl = string.Format(
CultureInfo.InvariantCulture,
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}",
this.facebookApiClientId,
this.GetLoginAbsoluteUrl(),
this.facebookApiClientSecret,
code);
var accessToken = string.Empty;
try
{
using (var client = new WebClient())
{
var receivedStream = client.OpenRead(tokenUrl);
using (var tokenReader = new StreamReader(receivedStream))
{
accessToken = tokenReader.ReadToEnd();
var userProfileUrl = new Uri(string.Format("{0}?{1}", FacebookApiProfileUrl, accessToken));
receivedStream = client.OpenRead(userProfileUrl);
using (var profileReader = new StreamReader(receivedStream))
{
receivedStream = client.OpenRead(userProfileUrl);
var result = profileReader.ReadToEnd();
var userProfile = new JavaScriptSerializer().Deserialize<dynamic>(result);
FormsAuthentication.SetAuthCookie(userProfile["name"], createPersistentCookie: true);
return Redirect(string.IsNullOrEmpty(state) ? "~/" : HttpUtility.UrlDecode(state));
}
}
}
}
catch (Exception)
{
// TODO: Handle appropiate error.
return Redirect("~/");
}
}
示例10: Start
private void Start(object o)
{
try
{
Station station = (Station)o;
WebClient client = new WebClient();
Stream openRead = client.OpenRead(String.Format(ConfigurationService.ShoutcastPlaylistURL, station.ID));
StreamReader reader = new StreamReader(openRead);
bool foundIP = false;
while (!reader.EndOfStream && !foundIP)
{
string line = reader.ReadLine();
Regex regex = new Regex(@"(?<ip>[0-9]+.[0-9]+.[0-9]+.[0-9]+):(?<port>[0-9]+)");
Match match = regex.Match(line);
if (match.Success)
{
String IP = match.Groups["ip"].Value;
int port = Int32.Parse(match.Groups["port"].Value);
IPAddress parsedIPAddress = IPAddress.Parse(IP);
if (parsedIPAddress != null)
{
IPEndPoint endPoint = new IPEndPoint(parsedIPAddress, port);
PortProber prober = new PortProber(endPoint);
station.IsAlive = prober.ProbeMachine();
foundIP = true;
}
}
}
}
catch (Exception e) { }
}
示例11: download
private void download(string link, string path)
{
Uri url = new Uri(link);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(link)))
{
using (Stream streamLocal = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[8192];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
streamLocal.Write(byteBuffer, 0, iByteSize);
}
streamLocal.Close();
}
streamRemote.Close();
}
}
}
示例12: Update
/// <summary>
/// Downloads the specified web driver version.
/// </summary>
/// <param name="version">The version to download.</param>
protected override void Update(string version)
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip"))
using (var archive = new ZipArchive(stream))
archive.ExtractToDirectory(Path.Combine(ParentPath, version));
}
示例13: DownloadFromFtp
public static bool DownloadFromFtp(string fileName)
{
bool ret = true;
var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string path = Path.Combine(dirName, fileName);
try
{
var wc = new WebClient { Credentials = new NetworkCredential("solidk", "KSolid") };
var fileStream = new FileInfo(path).Create();
//string downloadPath = Path.Combine("ftp://194.84.146.5/ForDealers",fileName);
string downloadPath = Path.Combine(Furniture.Helpers.FtpAccess.resultFtp+"ForDealers", fileName);
var str = wc.OpenRead(downloadPath);
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
int readCount = str.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
fileStream.Write(buffer, 0, readCount);
readCount = str.Read(buffer, 0, bufferSize);
}
str.Close();
fileStream.Close();
wc.Dispose();
}
catch
{
ret = false;
}
return ret;
}
示例14: GetImageFromGravatar
public static void GetImageFromGravatar(string imageFileName, string email, int authorImageSize, FallBackService fallBack)
{
try
{
var baseUrl = String.Concat("http://www.gravatar.com/avatar/{0}?d=identicon&s=",
authorImageSize, "&r=g");
if (fallBack == FallBackService.Identicon)
baseUrl += "&d=identicon";
if (fallBack == FallBackService.MonsterId)
baseUrl += "&d=monsterid";
if (fallBack == FallBackService.Wavatar)
baseUrl += "&d=wavatar";
//hash the email address
var emailHash = MD5.CalcMD5(email.ToLower());
//format our url to the Gravatar
var imageUrl = String.Format(baseUrl, emailHash);
var webClient = new WebClient { Proxy = WebRequest.DefaultWebProxy };
webClient.Proxy.Credentials = CredentialCache.DefaultCredentials;
var imageStream = webClient.OpenRead(imageUrl);
cache.CacheImage(imageFileName, imageStream);
}
catch (Exception ex)
{
//catch IO errors
Trace.WriteLine(ex.Message);
}
}
示例15: GetListOfOperations
//DONE
//This method generates a list of operations from a web service description. Returns a list of the
//webservice's operations on success, and null on failure.
public string[] GetListOfOperations(string webServiceURL)
{
List<string> ListOfOperations = new List<string>();
WebClient webServiceClient = new WebClient();
Binding binding = new Binding();
try
{
Stream serviceStream = webServiceClient.OpenRead(webServiceURL + "?wsdl");
//This gets the WSDL file...
ServiceDescription webServiceDescription = ServiceDescription.Read(serviceStream);
//Get a list of operations from the web service description...
binding = webServiceDescription.Bindings[0];
OperationBindingCollection operationCollection = binding.Operations;
foreach (OperationBinding operation in operationCollection)
{
ListOfOperations.Add(operation.Name);
}
}
catch (Exception ex)
{
throw ex;
}
return ListOfOperations.ToArray();
}