C#.NET 网络操作类

 

using System;
using System.Web;
using System.Text;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Web.UI;

namespace Pub.Class
{
/// <summary>
/// 网络操作类
/// </summary>
public class Net
{
private static object lockHelper = new object();

#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;
}

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>
/// <code>
/// TimeSpan oStartTime=DateTime.Now.TimeOfDay;
/// Response.Write(GetHttpFile("http://www.spbdev.com/download/DotNetInfo1.0.rar",Request.MapPath("RecievedFile.rar")));
/// Response.Write("&lt;br>&lt;br>\r\n执行时间:" + DateTime.Now.TimeOfDay.Subtract(oStartTime).TotalMilliseconds.ToString() + " 毫秒");
/// </code>
/// </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

#region GetRemoteHtmlCode/GetRemoteHtmlCode2/GetRemoteHtmlCode3
/// <summary>
/// 获取远程文件源代码 GetRemoteHtmlCode(@"http://www.baidu.com");
/// </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(@"http://www.baidu.com");
/// </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(@"http://www.baidu.com");
/// </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(@"http://www.baidu.com");
/// </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

#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
}
}

 

posted @ 2010-07-05 21:48  熊哥  阅读(891)  评论(0编辑  收藏  举报