试用Spire.Xls读取Execl文件或IO,导出到 DataTable。

public DataTable ReadExecl(string fileName)
{
	using (var workbook = new Spire.Xls.Workbook())
	{
		workbook.LoadFromFile(fileName);
		using (var sheet = workbook.Worksheets[0])
		{
			return sheet.ExportDataTable();
		}
	}
}

Ping 域名或者IP地址,判读是否能正常连接到目标服务器。建议执行循环3~5次,取平均值判断网络延时更准确。

实例:

public static void SimplePing ()
{
    Ping pingSender = new Ping ();
    PingReply reply = pingSender.Send ("www.24kplus.com");

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine ("Address: {0}", reply.Address.ToString ());
        Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
        Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
        Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
        Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
    }
    else
    {
        Console.WriteLine (reply.Status);
    }
}

该组件允许用户通过IP地址查询是否VPN代理、开放代理、Web代理、Tor出口、数据中心、Web主机(DCH)范围和搜索引擎机器人(SES),组件从 ip2proxy bin 数据文件中查询代理IP信息。

文件下载:

IP2Proxy 组件: https://down.24kplus.com/dev/ip2proxy-1.0.0.0.zip

免费 IP2Proxy BIN 数据: https://lite.ip2location.com

商业 IP2Proxy BIN 数据: https://www.ip2location.com/database/ip2proxy

要求

Microsoft .NET 4.0 framework 或更高 / Microsoft .NET Core 2.0 或更高.

方法

方法名
描述
Close
关闭并清理文件缓存
GetPackageVersion
获取软件包版本(PX1到PX8的1到8)
GetDatabaseVersion
获取数据库版本
ProxyQuery
代理信息查询

属性

属性名
描述
UseMemoryMappedFile
设置或获取是否使用内存映射文件(MMF)
MapFileName
内存映射文件名(仅Win32平台有效)
ProxyDatabasePath
代理数据库文件位置
IsProxy
检查IP地址是否是代理
  • -1:错误
  • 0:非代理
  • 1:代理
  • 2:数据中心IP地址或搜索引擎机器人
ProxyType
代理类型
  • VPN
  • TOR
  • DCH
  • PUB*
  • WEB
  • SES

示例

static void Main(string[] args)
{
	using (var component = new IP2Proxy.Component())
	{
		component.ProxyDatabasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IP2PROXY-PX8.BIN");
		component.UseMemoryMappedFile = true;
		var proxy = component.ProxyQuery("58.220.95.56");

		Console.WriteLine("IsProxy: " + proxy.IsProxy.ToString());
		Console.WriteLine("ProxyType: " + proxy.ProxyType);
		Console.WriteLine("CountryCode: " + proxy.CountryCode);
		Console.WriteLine("Country: " + proxy.Country);
		Console.WriteLine("Region: " + proxy.Region);
		Console.WriteLine("City: " + proxy.City);
		Console.WriteLine("ISP: " + proxy.ISP);
		Console.WriteLine("Domain: " + proxy.Domain);
		Console.WriteLine("UsageType: " + proxy.UsageType);
		Console.WriteLine("ASN: " + proxy.ASN);
		Console.WriteLine("AS: " + proxy.AS);
		Console.WriteLine("LastSeen: " + proxy.LastSeen);
	}
	Console.ReadKey();
}

Whois 简单来说,就是一个用来查询域名是否已经被注册,以及注册域名的详细信息的数据库(如域名所有人、域名注册商、域名注册日期和过期日期等)。通过域名Whois服务器查询,可以查询域名归属者联系方式,以及注册和到期时间。

以下为 C# 域名 Whois 查询代码

public static string Whois(string domain)
{
	if (domain == null)
		throw new ArgumentNullException();
	int ccStart = domain.LastIndexOf(".");
	if (ccStart < 0 || ccStart == domain.Length)
		throw new ArgumentException();
	string ret = "";
	Socket s = null;
	try
	{
		string cc = domain.Substring(ccStart + 1);
		s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		s.Connect(new IPEndPoint(Dns.GetHostEntry(cc + ".whois-servers.net").AddressList[0], 43));
		s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
		byte[] buffer = new byte[1024];
		int recv = s.Receive(buffer);
		while (recv > 0)
		{
			ret += Encoding.ASCII.GetString(buffer, 0, recv);
			recv = s.Receive(buffer);
		}
		s.Shutdown(SocketShutdown.Both);
	}
	catch
	{
		throw new SocketException();
	}
	finally
	{
		if (s != null)
			s.Close();
	}
	return ret;
}

调用事例:

[TestMethod]
public void TestWhoisMethod()
{
	string whois = Whois("24kplus.com");
	Debug.WriteLine(whois);
	Console.ReadKey();
}

结果:

   Server Name: 24KPLUS.COM
   IP Address: 34.92.152.179
   Registrar: DNSPod, Inc.
   Registrar WHOIS Server: whois.dnspod.com
   Registrar URL: http://www.dnspod.cn

   Domain Name: 24KPLUS.COM
   Registry Domain ID: 2377863045_DOMAIN_COM-VRSN
   Registrar WHOIS Server: whois.dnspod.com
   Registrar URL: http://www.dnspod.cn
   Updated Date: 2019-07-05T12:32:38Z
   Creation Date: 2019-04-08T03:16:41Z
   Registry Expiry Date: 2023-04-08T03:16:41Z
   Registrar: DNSPod, Inc.
   Registrar IANA ID: 1697
   Registrar Abuse Contact Email: abuse@dnspod.com
   Registrar Abuse Contact Phone: +86.95716
   Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
   Name Server: F1G1NS1.DNSPOD.NET
   Name Server: F1G1NS2.DNSPOD.NET
   DNSSEC: unsigned
   URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/
>>> Last update of whois database: 2019-08-25T11:21:50Z <<<

For more information on Whois status codes, please visit https://icann.org/epp

NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar.  Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.

TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability.  VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.

The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.

Spire.XLS for .NET

Spire.XLS for .NET 是一个独立的 Excel 组件,不依赖于 Microsoft Office Excel。它同时支持旧版的 Excel 97-2003(.xls) 格式文档和新版的 Excel 2007、Excel 2010、Excel 2013、Excel 2016(.xlsx, .xlsb, .xlsm) 以及 Open Office(.ods) 格式文档。

Spire.XLS for .NET 提供免费版和商业版,根据需要自行定夺,本站不给予任何授权和破解支持。官网:http://www.e-iceblue.cn/

以下是简单的 Execl 文件打印例子:

/// <summary>
/// 打印 Execl
/// </summary>
/// <param name="fileName">要打印的 Execl 文件</param>
/// <param name="documentName">打印机上显示的文件名称</param>
/// <param name="printerName">打印机全名</param>
/// <param name="paperName">纸张名称(默认:A4)</param>
/// <param name="landscape">是否横向打印(默认:false)</param>
/// <param name="copies">打印份数(默认:1)</param>
public static void PrintExecl(string fileName, string documentName, string printerName, string paperName = "A4", bool landscape = false, short copies = 1)
{
	using (Spire.Xls.Workbook workbook = new Spire.Xls.Workbook())
	{
		//加载要打印的execl
		workbook.LoadFromFile(fileName);
		//打印机全名
		workbook.PrintDocument.PrinterSettings.PrinterName = printerName;
		//打印机上显示的文件名称
		workbook.PrintDocument.DocumentName = documentName;
		//打印份数
		workbook.PrintDocument.PrinterSettings.Copies = copies;
		//设定纸张大小
		foreach (PaperSize pageSize in workbook.PrintDocument.PrinterSettings.PaperSizes)
		{
			if (pageSize.PaperName == paperName)
			{
				workbook.PrintDocument.PrinterSettings.DefaultPageSettings.PaperSize = pageSize;
			}
		}
		//是否横向打印
		workbook.PrintDocument.PrinterSettings.DefaultPageSettings.Landscape = landscape;
		//打印
		workbook.PrintDocument.Print();
	}
}

C# .NET 利用 HttpWebRequest 模拟浏览器 http、https 请求。

/// <summary>
/// Http 请求
/// </summary>
/// <param name="url">url地址</param>
/// <param name="data">请求参数(可选参数)</param>
/// <param name="method">请求方法(可选参数,默认:GET)</param>
/// <param name="timeout">连接超时(可选参数,默认: 100,000 毫秒(100 秒))</param>
/// <param name="encoding">编码(可选参数,默认:utf-8)</param>
/// <param name="contentType">Content-type HTTP 标头(可选参数)</param>
/// <param name="userAgent">模拟浏览器UA(可选参数)</param>
/// <param name="headers">HTTP 标头(可选参数)</param>
/// <returns>远程服务器返回的数据</returns>
public static string HttpRequest(string url, string data = null, string method = "GET", int? timeout = null, Encoding encoding = null, string contentType = "application/x-www-form-urlencoded", string userAgent = null, Dictionary<string, string> headers = null)
{
	encoding = encoding ?? Encoding.UTF8;
	var myWebRequest = (HttpWebRequest)WebRequest.Create(url);
	myWebRequest.ContentType = contentType;
	myWebRequest.Method = method;
	if (!string.IsNullOrWhiteSpace(userAgent))
	{
		myWebRequest.UserAgent = userAgent;
	}
	if (timeout.HasValue)
	{
		myWebRequest.Timeout = timeout.Value;
	}
	if (myWebRequest.RequestUri.Scheme == "https")
	{
		myWebRequest.ProtocolVersion = HttpVersion.Version11;
		myWebRequest.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallback);
		// 这里设置了协议类型。
		ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
		myWebRequest.KeepAlive = false;
		ServicePointManager.CheckCertificateRevocationList = true;
		ServicePointManager.DefaultConnectionLimit = 100;
		ServicePointManager.Expect100Continue = false;
	}
	if (headers != null && headers.Count > 0)
	{
		foreach (KeyValuePair<string, string> item in headers)
		{
			myWebRequest.Headers[item.Key] = item.Value;
		}
	}
	try
	{
		if (!string.IsNullOrWhiteSpace(data))
		{
			using (Stream stream = myWebRequest.GetRequestStream())
			{
				var bytes = encoding.GetBytes(data);
				stream.Write(bytes, 0, bytes.Length);
				stream.Flush();
			}
		}
		using (HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
		{
			if (myWebResponse.StatusCode == HttpStatusCode.OK)
			{
				using (Stream receiveStream = myWebResponse.GetResponseStream())
				{
					using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
					{
						return readStream.ReadToEnd();
					}
				}
			}
			else
			{
				throw new WebException(myWebResponse.StatusDescription);
			}
		}
	}
	catch (Exception ex)
	{
		throw ex;
	}
	finally
	{
		myWebRequest.Abort();
	}
}
/// <summary>
/// (SSL) 证书验证回调
/// </summary>
/// <param name="sender">一个对象,它包含此验证的状态信息。</param>
/// <param name="certificate">用于对远程方进行身份验证的证书。</param>
/// <param name="chain">与远程证书关联的证书颁发机构链。</param>
/// <param name="sslPolicyErrors">与远程证书关联的一个或多个错误。</param>
/// <returns>是否接受指定证书进行身份验证</returns>
private static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
	if (sslPolicyErrors == SslPolicyErrors.None)
		return true;

	Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
	return false;
}

IP地址转数字

public long IPToNumber(string ip)
{
	string[] arrayIP = ip.Split('.');
	long sip1 = long.Parse(arrayIP[0]);
	long sip2 = long.Parse(arrayIP[1]);
	long sip3 = long.Parse(arrayIP[2]);
	long sip4 = long.Parse(arrayIP[3]);
	long ipNum = sip1 * 256 * 256 * 256 + sip2 * 256 * 256 + sip3 * 256 + sip4;
	return ipNum;
}

数字转IP地址

public string NumberToIP(long ipNum)
{
	StringBuilder builder = new StringBuilder();
	builder.Append((ipNum >> 24) & 0xFF).Append(".");
	builder.Append((ipNum >> 16) & 0xFF).Append(".");
	builder.Append((ipNum >> 8) & 0xFF).Append(".");
	builder.Append(ipNum & 0xFF);
	return builder.ToString();
}

.NET 版 Chromium WebBrowser 动态设置 http, https, socks5 代理方法。

private void InitWebBrowser(string url)
{
	ChromiumWebBrowser browser = new ChromiumWebBrowser(url);
	browser.Dock = DockStyle.Fill;
	//绑定 WebBrowser 初始化完成事件
	browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
	//添加到WinForm中
	this.Controls.Add(browser);
	browser.BringToFront();
}

private void Browser_IsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs e)
{
	if(e.IsBrowserInitialized)
	{
		//只能在WebBrowser UI呈现后获取 Request 上下文
		Cef.UIThreadTaskFactory.StartNew(delegate
		{
			//获取 Request 上下文
			var rc = browser.GetBrowser().GetHost().RequestContext;
			var dict = new Dictionary<string, object>();
			dict.Add("mode", "fixed_servers");
			dict.Add("server", "127.0.0.1:1080");
			string error;
			//设置代理
			rc.SetPreference("proxy", dict, out error);
			//如果 error 不为空则表示设置失败。
			if(!string.IsNullOrWhiteSpace(error))
			{
				MessageBox.Show(error, "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		});
	}
}

不要在 Cef.Initialize 时设置 CefCommandLineArgs.Add("proxy-server", "127.0.0.1:1080");,否则修改代理设置会失败。

利用 shell32 API清除IE缓存。好处是调用系统原生清理,保证效果,不好的就是会弹出窗口,影响用户体验。

public class ShellUtil
{
	[DllImport("shell32.dll")]
	public static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);
}

public enum ShowCommands : int
{
	SW_HIDE = 0,
	SW_SHOWNORMAL = 1,
	SW_NORMAL = 1,
	SW_SHOWMINIMIZED = 2,
	SW_SHOWMAXIMIZED = 3,
	SW_MAXIMIZE = 3,
	SW_SHOWNOACTIVATE = 4,
	SW_SHOW = 5,
	SW_MINIMIZE = 6,
	SW_SHOWMINNOACTIVE = 7,
	SW_SHOWNA = 8,
	SW_RESTORE = 9,
	SW_SHOWDEFAULT = 10,
	SW_FORCEMINIMIZE = 11,
	SW_MAX = 11
}

1、 清除IE临时文件

ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 255", "", ShowCommands.SW_HIDE);

2、清除IE Cookies

ShellUtil.ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 2", "", ShowCommands.SW_HIDE);

3、清除IE History

ShellUtil.ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 1", "", ShowCommands.SW_HIDE);

using System;
using System.Data.SqlTypes;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace utility
{
    /// <summary>
    /// Xml序列化与反序列化
    /// </summary>
    public class XmlUtil
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml) where T : new()
        {
            try
            {
                using (Stream sr = new FileStream(xml, FileMode.Open))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch
            {
                return default(T);
            }
        }
		
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer<T>(T obj)
        {
            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(typeof(T));
                try
                {
                    //序列化对象
                    xml.Serialize(Stream, obj);
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                Stream.Position = 0;
                using (StreamReader sr = new StreamReader(Stream))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}