本文整理汇总了C#中System.Net.WebClient.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.Dispose方法的具体用法?C# WebClient.Dispose怎么用?C# WebClient.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: download
void download(object o)
{
WebClient wc = null;
try
{
List<object> obj = (List<object>)o;
string uri = (string)obj[0];
string local = (string)obj[1];
Song song = (Song)obj[2];
int diff = (int)obj[3];
wc = new WebClient();
wc.Proxy = null;
wc.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);
wc.DownloadFile(uri, local);
if (downloadFinish != null)
{
downloadFinish.Invoke(song, diff);
}
wc.Dispose();
}
catch (ThreadAbortException)
{
if (wc != null)
{
wc.Dispose();
}
}
catch (Exception)
{
if (wc != null)
{
wc.Dispose();
}
}
}
示例2: button1_Click
//get new image
private void button1_Click(object sender, EventArgs e)
{
//rolling for random image
int id = ids[r.Next(ids.Length)];
FileInfo f = new FileInfo(Path.Combine(appdir, id + ".jpg"));
//TODO: work on the existing picture logic
//if (!f.Exists) {
//}
//downloading json file into a string
WebClient wc = new WebClient();
string s;
try {
s = wc.DownloadString("https://www.gstatic.com/prettyearth/assets/data/" + id + ".json");
} catch (Exception ex) {
Console.WriteLine(ex.StackTrace);
wc.Dispose();
return;
}
wc.Dispose();
//converting json file to object
Location loc = JsonConvert.DeserializeObject<Location>(s);
//saving image from json to a local file
loc.getImage().Save(f.FullName, System.Drawing.Imaging.ImageFormat.Jpeg);
lblId.Text = "ID: " + loc.id;
lblLoc.Text = loc.geocode.ToString();
//setting wallpaper
SystemParametersInfo(0x14, 0, f.FullName, 0x01 | 0x02);
}
示例3: LoadDocumentFromURI
/// <summary>
///
/// </summary>
/// <param name="UriStr"></param>
private void LoadDocumentFromURI(String UriStr)
{
if (!_downloading)
{
_client = new WebClient();
_client.DownloadProgressChanged += _client_DownloadProgressChanged;
_client.DownloadDataCompleted += _client_DownloadDataCompleted;
try
{
// запускаем загрузку
_client.DownloadDataAsync(new Uri(UriStr));
_downloading = true;
//DownloadBtn.Text = "Отменить";
}
catch (UriFormatException ex)
{
OperationResult = ex.Message;
_client.Dispose();
}
catch (WebException ex)
{
OperationResult = ex.Message;
_client.Dispose();
}
}
else
{
_client.CancelAsync();
}
}
示例4: GetNodes
/// <summary>
/// Parses and returns an array of nodes grabbed from https://wiki.tox.im/Nodes. Only use this if you're desperate.
/// </summary>
/// <returns></returns>
public static ToxNode[] GetNodes()
{
WebClient client = new WebClient();
string content = "";
try
{
content = client.DownloadString("https://wiki.tox.im/Nodes");
client.Dispose();
}
catch
{
client.Dispose();
return new ToxNode[0];
}
var list = new List<ToxNode>();
int index = content.IndexOf("<table");
string table = content.Substring(index, content.IndexOf("</table") - index + "</table".Length);
for (int i = 0; i < table.Length; i++)
{
if (table[i] != '<')
continue;
if (string.Concat(table[i], table[i+1], table[i+2]) == "<tr")
{
index = table.IndexOf(">", i + 3) + 1;
string row = table.Substring(index, table.IndexOf("</tr>", i) - index).Replace("\n", "");
if (row.StartsWith("<th"))
continue;
string[] cells = new string[7];
int count = 0;
for (int j = 0; j < row.Length; j++)
{
if (row[j] != '<')
continue;
if (string.Concat(row[j], row[j + 1], row[j + 2], row[j + 3]) == "<td>")
{
index = row.IndexOf("<td>", j) + 4;
string cell = row.Substring(index, row.IndexOf("</td>", j) - index);
cells[count] = cell;
count++;
}
}
list.Add(new ToxNode(cells[0], int.Parse(cells[2]), new ToxKey(ToxKeyType.Public, cells[3])));
}
}
return list.ToArray();
}
示例5: genBtn_Click
private void genBtn_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
try
{
client.DownloadString(webUrl.Text);
}
catch (Exception WTFBBQ) //Yes, I know WTFBBQ is never used, tysm VS! Now shut up. -DeathRight
{
client.Dispose();
MessageBox.Show("The URL specified, \"" + webUrl.Text + "\" does not exist.", "Why did you give me a invalid URL?!");
return;
}
client.Dispose();
/*if (String.IsNullOrWhiteSpace(serverName.Text))
{
MessageBox.Show("Sorry, but I don't think that \"" + serverName.Text + "\" is a very good name.\r\nTry again, only this time, do it properly, noob.", "Interesting choice of a server name");
return;
}
else*/ if (serverName.Text == "MapleStory")
{
MessageBox.Show("Is Nexon using my Patch Creator?", "...Nexon?");
}
else if (serverName.Text == "MapleSEA")
{
MessageBox.Show("¿Está utilizando Nexon mi Creador Parche?", "...Nexon?");
}
if (String.IsNullOrWhiteSpace(startVer.Text))
{
MessageBox.Show("Enter a valid number, noob.", "Enter a valid number");
return;
}
try
{
int test = Convert.ToInt32(startVer.Text);
}
catch (Exception WTFBBQ)
{
MessageBox.Show("Enter a valid number, noob.", "Enter a valid number");
return;
}
WzSettingsManager SettingsMngr = new WzSettingsManager(System.IO.Path.Combine(Application.StartupPath, "PatcherSettings.wz"), typeof(Patcher_UserSettings), typeof(Patcher_AppSettings));
SettingsMngr.Load();
Patcher_UserSettings.CurrentVersion = Convert.ToInt32(startVer.Text);
Patcher_AppSettings.PatchURL = webUrl.Text;
Patcher_AppSettings.ServerName = serverName.Text;
Patcher_AppSettings.PatcherLogo = new Bitmap(logoPicture.Image);
AppSettings.Logo = new Bitmap(logoPicture.Image);
SettingsMngr.Save();
MessageBox.Show("It was saved to: "+Application.StartupPath+"\\PatcherSettings.wz","Patcher settings file generated successfully!");
}
示例6: Download
public async Task<bool> Download(string uri, string filename)
{
try
{
string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string downloadFilePath = Path.Combine(downloadPath, filename);
if (System.IO.File.Exists(downloadFilePath))
{
PlayVideo( downloadFilePath );
return true;
}
webClient = new WebClient();
webClient.DownloadDataCompleted += async (s, e) =>
{
if( e.Cancelled )
{
BTProgressHUD.Dismiss();
webClient.Dispose();
return;
}
var bytes = e.Result; // get the downloaded data
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = filename;
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, bytes); // writes to local storage
ALAssetsLibrary videoLibrary = new ALAssetsLibrary();
await videoLibrary.WriteVideoToSavedPhotosAlbumAsync( new Foundation.NSUrl( localPath ));
BTProgressHUD.Dismiss();
PlayVideo( localPath );
webClient.Dispose();
};
BTProgressHUD.Show("cancel", OnCancelDownload, "Downloading Media....",-1, ProgressHUD.MaskType.Black );
var url = new Uri(uri);
webClient.DownloadDataAsync(url);
return true;
}
catch( Exception ex )
{
return false;
}
}
示例7: Main
static void Main()
{
Console.WriteLine("The following program is going to download Logo-BASD.jpg to D:\\");
//Console.Write("Please enter the address in the internet including the exact file name: ");
string input = "http://www.devbg.org/img/Logo-BASD.jpg";//You coud try with Console.WriteLine() and to see exceptions messages.
WebClient myFile = new WebClient();
try
{
myFile.DownloadFile(input, @"D:\logo.jpg");
Console.WriteLine("The file was downloaded. Check D:\\logo.jpg");
}
catch (ArgumentException)
{
Console.WriteLine("The internet address was not valid.");
}
catch (Exception ex)
{
Console.WriteLine("There was a problem while downloding the file to your computer.");
Console.WriteLine(ex.Message);
}
finally
{
myFile.Dispose();
}
}
示例8: UpdateAsync
protected virtual void UpdateAsync(string url, string filename, bool silent, object userState)
{
WebClient client = null;
WorkingUI work = null;
try
{
if (silent == false)
{
work = new WorkingUI();
}
string updatedExePath = Path.Combine(Program.AppData, filename);
client = new WebClient();
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(updater_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(url), updatedExePath, new object[] { client, updatedExePath, silent, work, userState });
}
catch
{
if (client != null)
{
client.Dispose();
client = null;
}
if (silent == false)
{
work.Dispose();
}
throw;
}
}
示例9: UploadTextFile
/// <summary>
/// This method is used to upload a file to the specified URI.
/// </summary>
/// <param name="fileUrl">Specify the URL where the file will be uploaded to.</param>
/// <param name="fileName">Specify the name for the file to upload.</param>
/// <returns>Return true if the operation succeeds, otherwise return false.</returns>
public bool UploadTextFile(string fileUrl, string fileName)
{
WebClient client = new WebClient();
string fullFileUri = string.Format("{0}/{1}", fileUrl, fileName);
try
{
byte[] contents = System.Text.Encoding.UTF8.GetBytes(Common.Common.GenerateResourceName(Site, "FileContent"));
client.Credentials = new NetworkCredential(Common.Common.GetConfigurationPropertyValue("UserName1", Site), Common.Common.GetConfigurationPropertyValue("Password1", Site), Common.Common.GetConfigurationPropertyValue("Domain", Site));
if (fullFileUri.StartsWith("HTTPS", System.StringComparison.OrdinalIgnoreCase))
{
Common.Common.AcceptServerCertificate();
}
client.UploadData(fullFileUri, "PUT", contents);
}
catch (System.Net.WebException ex)
{
Site.Log.Add(
LogEntryKind.Debug,
string.Format("Cannot upload the file to the full URI {0}, the exception message is {1}", fullFileUri, ex.Message));
return false;
}
finally
{
if (client != null)
{
client.Dispose();
}
}
return true;
}
开发者ID:OfficeDev,项目名称:Interop-TestSuites,代码行数:40,代码来源:MS-FSSHTTP-FSSHTTPBManagedCodeSUTControlAdapter.cs
示例10: GetAllImages
public static List<ImageInfo> GetAllImages()
{
List<ImageInfo> imageInfoList = new List<ImageInfo>();
ImageInfoJson infoJson = GetAllGroupImages(1);
imageInfoList.AddRange(infoJson.ImageInfos);
for (int i = 2; i <= infoJson.Query.TotalPage; i++)
{
ImageInfoJson itemJson = GetAllGroupImages(i);
imageInfoList.AddRange(itemJson.ImageInfos);
}
WebClient webClient = new WebClient();
foreach (ImageInfo imageInfo in imageInfoList)
{
try
{
imageInfo.LocationUrl = FileUtils.DownloadImage(webClient, imageInfo.Url, imageInfo.Id);
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
imageInfo.LocationUrl = "";
}
}
webClient.Dispose();
return imageInfoList;
}
示例11: ImportMedia
public void ImportMedia(string fileUri)
{
var fileName = Path.GetFileName(fileUri);
var savePathForFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
if (!File.Exists(savePathForFile))
{
var client = new WebClient();
BinaryWriter binaryWriter = null;
try
{
byte[] data = client.DownloadData(fileUri);
var fileStream = new FileStream(savePathForFile, FileMode.Create, FileAccess.Write);
binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(data);
binaryWriter.Close();
}
finally
{
client.Dispose();
if (binaryWriter != null)
{
binaryWriter.Close();
}
}
}
}
示例12: HasUpdate
public static bool HasUpdate()
{
try
{
if (System.IO.File.Exists("Updater.exe"))
System.IO.File.Delete("Updater.exe");
myWebClient = new WebClient();
myWebClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
myWebClient.Headers.Add("Cache-Control", "no-cache");
NewVersion = myWebClient.DownloadString("http://mapeditor.npdev.eu/updates/core_version.txt");
myWebClient.Dispose();
if (NewVersion != ActVersion)
return true;
else
return false;
}
catch
{
return false;
}
}
示例13: ddos
private void ddos(string urls, string datatext)
{
url = urls;
try
{
HERE:
for (int j = 0; j < 100; ++j)
{
j = 0;
for (Int64 i = 0; i < 99999999; ++i)
{
var client = new WebClient();
client.DownloadStringAsync(new Uri(url));
dt += client;
client.Dispose();
dt += client;
}
Thread.Sleep(1000);
}
goto HERE;
}
catch(InsufficientMemoryException iEx)
{
MessageBox.Show(iEx.Message, iEx.StackTrace);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, ex.StackTrace);
}
}
示例14: UBox
private UBox()
{
try
{
WebClient wClient = new WebClient();
string localTmpFile = CurrentDirectory + "\\UBox.tmp";
wClient.DownloadFile(url, localTmpFile);
wClient.Dispose();
using (StreamReader sr = new StreamReader(localTmpFile, Encoding.Default))
{
string line;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
if (string.IsNullOrEmpty(line) || line.StartsWith("#"))
continue;
//string[] items = line.Split(':');
int index = line.IndexOf(":");
if (index != -1)
{
Maps.Add(line.Substring(0, index), line.Substring(index + 1));
}
}
sr.Close();
}
Thread.Sleep(1);
File.Delete(localTmpFile);//ɾ����ʱ�ļ�
}
catch
{
}
}
示例15: DownloadDatabase
public void DownloadDatabase(string targetFile, EventHandler successCallback)
{
WebClient wc = new WebClient();
wc.Headers.Set("Cookie", cookieContainer.GetCookieHeader(new Uri(baseURL)));
wc.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) {
output.BeginInvoke((MethodInvoker)delegate {
output.Text = "Download: " + e.ProgressPercentage + "%";
});
};
wc.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) {
output.BeginInvoke((MethodInvoker)delegate {
if (e.Error != null)
output.Text = e.Error.ToString();
else
output.Text = "Download complete.";
});
if (e.Error == null) {
using (FileStream fs = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) {
fs.Write(e.Result, 0, e.Result.Length);
}
successCallback(this, EventArgs.Empty);
}
wc.Dispose();
};
wc.DownloadDataAsync(new Uri(baseURL + "CompactNdownload.asp"));
}