要完成高性能的Web服务功能,通常都是需要用到服务,如:IIS、Apache、Tomcat和Nginx,但是众所周知的Web服务器配置的复杂性,如果我们只是需要一些简单的功能,安装这些组件看起来就没多大必要。我们需要的是一个简单的HTTP类,可以很容易地嵌入到简单的Web请求的服务,加到自己的程序里。

.net 框架下有一个简单但很强大的类 System.Net.HttpListener。这个类几行代码就能完成一个简单的服务器功能。

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8081/");
listener.Start();
Console.WriteLine("Listening...");
Task task = Task.Factory.StartNew(() => {
	while(listener.IsListening)
	{
		HttpListenerContext context = listener.GetContext();
		Console.WriteLine("Http requesting...");
		HttpListenerRequest request = context.Request;
		HttpListenerResponse response = context.Response;
		Console.WriteLine("Http responseting...");
		string responseString = "<html><title>Http server in C#</title><body><p>Hello world!</p></body></html>";
		using (StreamWriter writer = new StreamWriter(response.OutputStream))
		{
			writer.WriteLine(responseString);
		}
	}
});
task.Wait();

结果

http server

C# 读取 CSV 文件数据到 DataTable。

public static DataTable ReadCSVtoDataTable(string fileName)
{
	DataTable dt = new DataTable();
	Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
	using (StreamReader sr = new StreamReader(fileName))
	{
		string[] headers = sr.ReadLine().Split(',');
		foreach (string header in headers)
		{
			dt.Columns.Add(header);
		}
		while (sr.Peek() > 0)
		{
			string[] rows = regex.Split(sr.ReadLine());
			DataRow dr = dt.NewRow();
			for (int i = 0; i < headers.Length; i++)
			{
				dr[i] = rows[i];
			}
			dt.Rows.Add(dr);
		}
	}
	return dt;
}

DataTable 导出 CSV,支持.NET Framework 4.0以上。

public byte[] DataTableToCSV(DataTable data)
{
	StringBuilder sb = new StringBuilder();
	IEnumerable<string> columnNames = data.Columns.Cast<DataColumn>().
									  Select(column => column.ColumnName);
	sb.AppendLine(string.Join(",", columnNames));
	foreach (DataRow row in data.Rows)
	{
		IEnumerable<string> fields = row.ItemArray.Select(field =>
		  string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
		sb.AppendLine(string.Join(",", fields));
	}
	return System.Text.Encoding.Default.GetBytes(sb.ToString());
}

IP2Location for.net Standard 组件是一个基于 .net Standard 框架的软件开发组件和数据解决方案,它使您能够实时发现您的web访问者通过ip地址来自何处。然后您可以根据访问者的国家、地区、城市、纬度、经度、邮政编码、ISP、域名、时区、连接速度、IDD代码、区号、气象站代码、气象站名称、MCC、MNC、移动品牌名称、海拔和使用类型动态调整网站内容。

文件下载:

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

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

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

要求

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

方法

方法名
描述
Close
关闭并清理文件缓存
IPQuery
IP信息查询
Dispose
释放由 IP2Location 占用的资源。

属性

属性名
描述
UseMemoryMappedFile
设置或获取是否使用内存映射文件(MMF)
MapFileName
内存映射文件名(仅Win32平台有效)
IPDatabasePath
IP数据库文件位置
IPDatabaseVersion
IP数据库版本

示例

static void Main(string[] args)
{
	using (Component component = new Component())
	{
		component.IPDatabasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IP2LOCATION.BIN");
		IPResult result = component.IPQuery("58.220.95.56");
		Console.WriteLine("AreaCode: " + result.AreaCode);
		Console.WriteLine("CountryCode: " + result.CountryCode);
		Console.WriteLine("Country: " + result.Country);
		Console.WriteLine("Region: " + result.Region);
		Console.WriteLine("City: " + result.City);
		Console.WriteLine("Latitude: " + result.Latitude);
		Console.WriteLine("Longitude: " + result.Longitude);
		...
	}
	Console.ReadKey();
}

验证字符串是否为有效的电子邮件格式

示例

该示例定义 IsValidEmail 方法,如果字符串包含有效的电子邮件地址,则该方法返回 true ,否则返回 false ,但不采取其他任何操作。

请注意, IsValidEmail 方法不执行身份验证来验证电子邮件地址。 它只确定其格式对于电子邮件地址是否有效。 此外, IsValidEmail 方法不对顶级域名是否是 IANA 根区域数据中列出的有效域名进行验证,这需执行查找操作。 相反,正则表达式仅验证由二到二十四个 ASCII 字符组成的顶级域名,该域名以字母数字开头并以字符结尾,且其余的字符是字母数字或连字符 (-)。

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtil
{
    public static bool IsValidEmail(string email)
    {
        if (string.IsNullOrWhiteSpace(email))
            return false;

        try
        {
            // Normalize the domain
            email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                  RegexOptions.None, TimeSpan.FromMilliseconds(200));
        }
        catch (RegexMatchTimeoutException e)
        {
            return false;
        }
        catch (ArgumentException e)
        {
            return false;
        }

        try
        {
            return Regex.IsMatch(email,
                @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        }
        catch (RegexMatchTimeoutException)
        {
            return false;
        }
    }
    static string DomainMapper(Match match)
    {
        // Use IdnMapping class to convert Unicode domain names.
        var idn = new IdnMapping();

        // Pull out and process domain name (throws ArgumentException on invalid)
        var domainName = idn.GetAscii(match.Groups[2].Value);

        return match.Groups[1].Value + domainName;
    }
}

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();
	}
}