代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Asp.Net
】
NET 网络操作类
作者:
Dezai.CN
/ 发布于
2012/8/13
/
505
NET 网络操作类
<div>using System; using System.Web; using System.Text; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Web.UI;</div> <div>namespace Pub.Class { /// <summary> /// 网络操作类 /// </summary> public class Net { private static object lockHelper = new object();</div> <div> #region DownFile/ResponseFile/GetHttpFile /// <summary> /// 下载文件 /// </summary> /// <param name="fileFile">文件路径(绝对路径)</param> /// <returns >返回文件是否存在,存在下载成功</returns> public static bool DownFile(string fileFile) { if (System.IO.File.Exists(fileFile)) { FileInfo _DownloadFile = new FileInfo(fileFile); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = false; HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_DownloadFile.FullName, System.Text.Encoding.UTF8)); HttpContext.Current.Response.AppendHeader("Content-Length", _DownloadFile.Length.ToString()); HttpContext.Current.Response.WriteFile(_DownloadFile.FullName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); return true; } <div> return false; } public static string DownFile(string url,string fileName) { WebClient wc = new WebClient(); try { wc.DownloadFile(url,fileName); } catch { fileName = ""; } finally { wc.Dispose(); } return fileName; } /// <summary> /// 以指定的ContentType输出指定文件文件 /// </summary> /// <param name="filepath">文件路径</param> /// <param name="filename">输出的文件名</param> /// <param name="filetype">将文件输出时设置的ContentType</param> public static void ResponseFile(string filepath, string filename, string filetype) { Stream iStream = null; // 缓冲区为10k byte[] buffer = new Byte[10000]; // 文件长度 int length; // 需要读的数据长度 long dataToRead; try { // 打开文件 iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read,FileShare.Read); // 需要读的数据长度 dataToRead = iStream.Length; HttpContext.Current.Response.ContentType = filetype; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename.Trim().UrlEncode().Replace("+", " ")); while (dataToRead > 0) { // 检查客户端是否还处于连接状态 if (HttpContext.Current.Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10000); HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); HttpContext.Current.Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { // 如果不再连接则跳出死循环 dataToRead = -1; } } } catch (Exception ex) { HttpContext.Current.Response.Write("Error : " + ex.Message); } finally { if (iStream != null) iStream.Close();// 关闭文件 } HttpContext.Current.Response.End(); } /// <summary> /// 下载远程的文件 /// </summary> /// <param name="sUrl">URL</param> /// <param name="sSavePath">保存到</param> /// <returns>成功否</returns> /// <example> /// /// TimeSpan oStartTime=DateTime.Now.TimeOfDay; /// Response.Write(GetHttpFile("<a href="http://www.spbdev.com/download/DotNetInfo1.0.rar",Request.MapPath("RecievedFile.rar">http://www.spbdev.com/download/DotNetInfo1.0.rar",Request.MapPath("RecievedFile.rar</a>"))); /// Response.Write("<br><br>\r\n执行时间:" + DateTime.Now.TimeOfDay.Subtract(oStartTime).TotalMilliseconds.ToString() + " 毫秒"); /// /// </example> public bool GetHttpFile(string sUrl,string sSavePath) { string sException=null; bool bRslt=false; WebResponse oWebRps=null; WebRequest oWebRqst=WebRequest.Create(sUrl); oWebRqst.Timeout=50000; try{ oWebRps=oWebRqst.GetResponse(); } catch(WebException e){ sException=e.Message.ToString(); } catch(Exception e){ sException=e.ToString(); } finally { if(oWebRps!=null){ BinaryReader oBnyRd=new BinaryReader(oWebRps.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312")); int iLen=Convert.ToInt32(oWebRps.ContentLength); FileStream oFileStream; try{ if(File.Exists( HttpContext.Current.Request.MapPath("RecievedData.tmp"))) oFileStream=File.OpenWrite(sSavePath); else oFileStream=File.Create(sSavePath); oFileStream.SetLength((Int64)iLen); oFileStream.Write(oBnyRd.ReadBytes(iLen),0,iLen); oFileStream.Close(); } finally { oBnyRd.Close(); oWebRps.Close(); } bRslt=true; } } return bRslt; } #endregion</div> <div> #region GetRemoteHtmlCode/GetRemoteHtmlCode2/GetRemoteHtmlCode3 /// <summary> /// 获取远程文件源代码 GetRemoteHtmlCode(@"<a href="http://www.baidu.com">http://www.baidu.com</a>"); /// </summary> /// <param name="Url">远程url</param> /// <returns></returns> public static string GetRemoteHtmlCode2(string Url) { return GetRemoteHtmlCode2(Url, Encoding.Default); } /// <summary> /// 获取远程文件源代码 /// </summary> /// <param name="Url"></param> /// <param name="encoding"></param> /// <returns></returns> public static string GetRemoteHtmlCode2(string Url, System.Text.Encoding encoding) { lock (lockHelper) { Url += (Url.IndexOf("?") >= 0 ? "&time=" : "?time=") + Rand.RndDateStr(); string s = ""; HttpWebResponse response = null; StreamReader stream = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); response = (HttpWebResponse) request.GetResponse(); stream = new StreamReader(response.GetResponseStream(),encoding); s = stream.ReadToEnd(); } catch {} finally { if (stream != null) stream.Close(); if (response != null) response.Close(); } return s; } } /// <summary> /// 获取远程文件源代码 GetRemoteHtmlCode(@"<a href="http://www.baidu.com">http://www.baidu.com</a>"); /// </summary> /// <param name="strUrl">远程url</param> /// <returns></returns> public static string GetRemoteHtmlCode3(string strUrl) { return GetRemoteHtmlCode3(strUrl, Encoding.Default); } /// <summary> /// 获取远程文件源代码 /// </summary> /// <param name="strUrl"></param> /// <param name="encoding"></param> /// <returns></returns> public static string GetRemoteHtmlCode3(string strUrl, System.Text.Encoding encoding) { lock (lockHelper) { strUrl += (strUrl.IndexOf("?") >= 0 ? "&time=" : "?time=") + Rand.RndDateStr(); StringBuilder Html = new StringBuilder(); HttpWebResponse myRp = null; StreamReader sr = null; Stream mystr = null; try { HttpWebRequest myRq = (HttpWebRequest)HttpWebRequest.Create(strUrl); myRq.AllowAutoRedirect = true; myRq.Timeout = 1000*60*3; myRq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; myRq.Referer=strUrl; myRp = (HttpWebResponse)myRq.GetResponse(); mystr = myRp.GetResponseStream(); sr = new StreamReader(mystr,encoding); while(sr.Peek()!=-1) { Html.Append(sr.ReadToEnd()); } } catch { return "-1"; } finally { if (sr!=null) sr.Close(); if (mystr!=null) mystr.Close(); if (myRp!=null) myRp.Close(); } return Html.ToString(); } } /// <summary> /// 获取远程文件源代码 GetRemoteHtmlCode(@"<a href="http://www.baidu.com">http://www.baidu.com</a>"); /// </summary> /// <param name="strUrl">远程url</param> /// <returns></returns> public static string GetRemoteHtmlCode4(string strUrl) { return GetRemoteHtmlCode4(strUrl, Encoding.Default); } /// <summary> /// 获取远程文件源代码 /// </summary> /// <param name="Url"></param> /// <param name="encoding"></param> /// <returns></returns> public static string GetRemoteHtmlCode4(string Url, System.Text.Encoding encoding) { lock (lockHelper) { Url += (Url.IndexOf("?") >= 0 ? "&time=" : "?time=") + Rand.RndDateStr(); WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; Byte[] pageData = wc.DownloadData(Url); string content = encoding.GetString(pageData); wc.Dispose(); return content; } } /// <summary> /// 获取远程文件源代码 GetRemoteHtmlCode(@"<a href="http://www.baidu.com">http://www.baidu.com</a>"); /// </summary> /// <param name="strUrl">远程url</param> /// <returns></returns> public static string GetRemoteHtmlCode5(string strUrl) { return GetRemoteHtmlCode5(strUrl, Encoding.Default); } /// <summary> /// 获取远程文件源代码 /// </summary> /// <param name="Url"></param> /// <param name="encoding"></param> /// <returns></returns> public static string GetRemoteHtmlCode5(string Url, System.Text.Encoding encoding) { lock (lockHelper) { Url += (Url.IndexOf("?") >= 0 ? "&time=" : "?time=") + Rand.RndDateStr(); string postString = ""; WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] postData = Encoding.ASCII.GetBytes(postString); byte[] responseData = webClient.UploadData(Url, "POST", postData); string srcString = encoding.GetString(responseData); webClient.Dispose(); return srcString; } } #endregion</div> <div> #region TransHtml /// <summary> /// 转换为静态html /// </summary> public static void TransHtml(string path, string outpath,System.Text.Encoding encoding) { lock (lockHelper) { FileStream stream = null; StringWriter writer = new StringWriter(); try { Page page = new Page(); page.Server.Execute(path, writer); if (File.Exists(outpath)) { File.Delete(outpath); stream = File.Create(outpath); } else { stream = File.Create(outpath); } byte[] bytes = encoding.GetBytes(writer.ToString()); stream.Write(bytes, 0, bytes.Length); } catch {} finally{ if (writer != null) { writer.Close(); writer.Dispose(); } if (stream != null) { stream.Close(); stream.Dispose(); } } } } #endregion } }
试试其它关键字
NET
网络操作类
同语言下
.
gzip压缩
.
实现http多线程断点续传下载文件
.
实现多线程断点续传下载大文件
.
生成字符串的 CheckSum
.
根据 UserAgent 获取浏览器的类型和版本
.
根据 Agent 判断是否是智能手机
.
隐藏手机号中间四位为*方法
.
合并图片(二维码和其他图片合并)
.
ASP.NET CORE中判断是否移动端打开网页
.
ASP.NET(C#)实现页面计时(定时)自动跳转
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Dezai.CN
贡献的其它代码
(
4037
)
.
多线程Socket服务器模块
.
生成随机密码
.
清除浮动样式
.
弹出窗口居中
.
抓取url的函数
.
使用base HTTP验证
.
div模拟iframe嵌入效果
.
通过header转向的方法
.
Session操作类
.
执行sqlite输入插入操作后获得自动编号的ID
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3