C#版ip2long和long2ip

public static long ip2long(string ipAddress) 
{
    try

    {
       System.Net.IPAddress ip = System.Net.IPAddress.Parse(ipAddress); 
       return (((long)ip.GetAddressBytes()[0] < < 24) | ((int)ip.GetAddressBytes()[1] << 16) | ((int)ip.GetAddressBytes()[2] << 8) | ip.GetAddressBytes()[3]); 
    }
    catch (Exception) 
    {
        return 0; 
    }
}

public static string long2ip(long ipAddress) 
{
    try

    {
        System.Net.IPAddress tmpIp = System.Net.IPAddress.Parse(ipAddress.ToString()); 
        Byte[] bytes = tmpIp.GetAddressBytes();   
        long addr = (long)BitConverter.ToInt32(bytes, 0);
        return new System.Net.IPAddress(addr).ToString(); 
    }
    catch (Exception e) { return e.Message; } 
}

各种编程语言中获取与转换Unix时间戳(Unix timestamp)

如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)?

Java time
JavaScript Math.round(new Date().getTime()/1000)
getTime()返回数值的单位是毫秒
Microsoft .NET / C# epoch = (DateTime.Now.ToUniversalTime().Ticks – 621355968000000000) / 10000000
MySQL SELECT unix_timestamp(now())
Perl time
PHP time()
PostgreSQL SELECT extract(epoch FROM now())
Python 先 import time 然后 time.time()
Ruby 获取Unix时间戳:Time.now 或 Time.new
显示Unix时间戳:Time.now.to_i
SQL Server SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, GETUTCDATE())
Unix / Linux date +%s
VBScript / ASP DateDiff(“s”, “01/01/1970 00:00:00”, Now())
其他操作系统
(如果Perl被安装在系统中)
命令行状态:perl -e “print time”

如何在不同编程语言中实现Unix时间戳(Unix timestamp) → 普通时间?

Java String date = new java.text.SimpleDateFormat(“dd/MM/yyyy HH:mm:ss”).format(new java.util.Date(Unix timestamp * 1000))
JavaScript 先 var unixTimestamp = new Date(Unix timestamp * 1000) 然后 commonTime = unixTimestamp.toLocaleString()
Linux date -d @Unix timestamp
MySQL from_unixtime(Unix timestamp)
Perl 先 my $time = Unix timestamp 然后 my ($sec, $min, $hour, $day, $month, $year) = (localtime($time))[0,1,2,3,4,5,6]
PHP date(‘r’, Unix timestamp)
PostgreSQL SELECT TIMESTAMP WITH TIME ZONE ‘epoch’ + Unix timestamp) * INTERVAL ‘1 second’;
Python 先 import time 然后 time.gmtime(Unix timestamp)
Ruby Time.at(Unix timestamp)
SQL Server DATEADD(s, Unix timestamp, ‘1970-01-01 00:00:00’)
VBScript / ASP DateAdd(“s”, Unix timestamp, “01/01/1970 00:00:00”)
其他操作系统
(如果Perl被安装在系统中)
命令行状态:perl -e “print scalar(localtime(Unix timestamp))”

Visual Studio Team System 2008 Team Suite 迅雷下载

Visual Studio Team System 2008 Team Suite 迅雷下载地址:
ed2k://|file|zh-Hans_visual_studio_team_system_2008_team_suite_x86_x64wow_dvd_X14-26452.iso|4663904256|8E2D6430D819328940B9BF83568589FA|h=EEIMYZRV4MPHLRU2XW3FVLV6ZGV7XH7U|/

正版序列号:
PYHYP-WXB3B-B2CCM-V9DX9-VDY8T

破解方法:
开始> 设置> 控制面版> 添加或删除程序> 卸载vs.net2008> 选择升级选项> 输入正版序列号
点击升级,完成!

注意:在WIN7,WIN2008 SERVER等系统中,卸载界面是没有显示出输入序列号的地方,微软将输入的位置隐藏起来了。
那么在WIN7或WIN2008系统中,如何升级输入序列号呢?我们需要借CrackVS2008ForWindows7.zip这个工具,将隐藏的输入框找回来。

具体的操作方法如下:
1. 安装 VS2008 (如果你已经安装了,那忽略此项)
2. 打开 控制面板 –> 添加删除程序, 找到 VS2008 的安装项,运行 VS2008的安装卸载程序,出现如下的界面
clip_image001

clip_image003
3. 打开CrackVS2008ForWindows7破解程序,出现如下的界面
clip_image004
4. 点击上面的 “Bug 微软”,随即将出现升级输入序列号输入框
clip_image006

输入序列号并点击升级按钮,完成!

使用C#发送电子邮件

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(this.txtTo.Text);
mailMessage.From = new System.Net.Mail.MailAddress(this.txtFrom.Text);
mailMessage.Subject = this.txtTitle.Text;
mailMessage.Body = this.txtContent.Text;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
 
SmtpClient smtpClient = new SmtpClient();
smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, this.txtPassword.Text);
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host = "smtp." + mailMessage.From.Host;
smtpClient.Port = 25;
smtpClient.Timeout = 3000;
smtpClient.EnableSsl = false;
smtpClient.Send(mailMessage);

C#获取CPU和硬盘的序列号

using System.Management;
using System.Management.Instrumentation;

private void GetInfo()  
{  
    string cpuInfo = "";//cpu序列号  
    ManagementClass cimobject = new ManagementClass("Win32_Processor");  
    ManagementObjectCollection moc = cimobject.GetInstances();  
    foreach(ManagementObject mo in moc)  
    {  
     cpuInfo = mo.Properties["ProcessorId"].Value.ToString();  
     Response.Write ("cpu序列号:"+cpuInfo.ToString ());  
    }  

    //获取硬盘ID  
    String HDid;  
    ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");  
    ManagementObjectCollection moc1 = cimobject1.GetInstances();  
    foreach(ManagementObject mo in moc1)  
    {  
     HDid = (string)mo.Properties["Model"].Value;  
     Response.Write ("硬盘序列号:"+HDid.ToString ());  
    }  


    //获取网卡硬件地址  

     
     
    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");  
    ManagementObjectCollection moc2 = mc.GetInstances();  
    foreach(ManagementObject mo in moc2)  
    {  
     if((bool)mo["IPEnabled"] == true)  
      Response.Write("MAC address\t{0}"+mo["MacAddress"].ToString());  
     mo.Dispose();  
    }  
}

C#DOS命令输出类

using System.Diagnostics;

/// 
/// DOS命令输出类
/// 
public class CommandDo
{
    /**/
    /// 
    /// 执行DOS命令,返回DOS命令的输出
    /// 
    /// dos命令
    /// 返回输出,如果发生异常,返回空字符串
    public static string Execute(string dosCommand)
    {
        return Execute(dosCommand, 6 * 1000);
    }
    /**/
    /// 
    /// 执行DOS命令,返回DOS命令的输出
    /// 
    /// dos命令
    /// 等待命令执行的时间(单位:毫秒),如果设定为0,则无限等待
    /// 返回输出,如果发生异常,返回空字符串
    public static string Execute(string dosCommand, int milliseconds)
    {
        string output = "";     //输出字符串
        if (dosCommand != null && dosCommand != "")
        {
            Process process = new Process();     //创建进程对象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "cmd.exe";      //设定需要执行的命令
            startInfo.Arguments = "/C "   dosCommand;   //设定参数,其中的“/C”表示执行完命令后马上退出
            startInfo.UseShellExecute = false;     //不使用系统外壳程序启动
            startInfo.RedirectStandardInput = false;   //不重定向输入
            startInfo.RedirectStandardOutput = true;   //重定向输出
            startInfo.CreateNoWindow = true;     //不创建窗口
            process.StartInfo = startInfo;
            try
            {
                if (process.Start())       //开始进程
                {
                    if (milliseconds == 0)
                        process.WaitForExit();     //这里无限等待进程结束
                    else
                        process.WaitForExit(milliseconds);  //这里等待进程结束,等待时间为指定的毫秒
                    output = process.StandardOutput.ReadToEnd();//读取进程的输出
                }
            }
            catch
            {
            }
            finally
            {
                if (process != null)
                    process.Close();
            }
        }
        return output;
    }
}

C#执行CMD命令并返回结果

private void button1_Click(object sender, EventArgs e)
{
// 调用代码
string[] cmd = new string[] { "ping 192.168.3.15 -n 1", "ping 192.168.3.16 -n 2" };
MessageBox.Show(Cmd(cmd));
CloseProcess("cmd.exe");
}

/// <summary>
/// 运行CMD命令
/// </summary>
/// <param name="cmd">命令</param>
/// <returns></returns>
public static string Cmd(string [] cmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
for (int i = 0; i < cmd.Length; i++)
{
p.StandardInput.WriteLine(cmd[i].ToString());
}
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return strRst;
}

/// <summary>
/// 关闭进程
/// 
/// <param name="ProcName">进程名称</param>
/// <returns></returns>
public static bool CloseProcess(string ProcName)
{
bool result = false;
System.Collections.ArrayList procList = new System.Collections.ArrayList();
string tempName = "";
int begpos;
int endpos;
foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
{
tempName = thisProc.ToString();
begpos = tempName.IndexOf("(") + 1;
endpos = tempName.IndexOf(")");
tempName = tempName.Substring(begpos, endpos - begpos);
procList.Add(tempName);
if (tempName == ProcName)
{
if (!thisProc.CloseMainWindow())
thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程
result = true;
}
}
return result;
}

Visual Studio 2008“Web 创作组件”安装失败的解决办法

网上这个的解决方法有很多,但大多都随便复制来复制去结果弄得乱七八糟,其实这问题是由于先安装了OFFICE2007而引起的,解决这问题很简单:

1. 准备两张安装光盘(镜像也行)

2. 插入VS2008的光盘,找到WCU/WebDesignerCore/WebDesignerCore.exe,这就是创作组件,把这文件用RAR解压到桌面上(装完后可以删)

3. 解压后,点击SETUP.EXE开始安装

4. 插入OFFICE2007光盘,当创作组件安装到提示找不到“Office.zh-ch”的时候,就选择路径为刚才插入的OFFICE2007光盘的根目录,确定后就可以顺利安装完成

5. 拔掉OFFICE2007的光盘,插入Visual Studio 2008的安装光盘,然后一切照常安装。

无法读取项目文件 .csproj,请确认 声明中的路径正确,且磁盘上存在该文件。

解决办法:将项目文件(.csproj)用记事本打开,然后找到节点,作如下操作:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

替换为:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

如果再不行,再试导入注册表:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\4.0]
"DefaultToolsVersion"="2.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0]
"MSBuildToolsPath"="C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0]
"MSBuildToolsPath"="C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\"

C#批处理图片尺寸(按文件夹)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace ThumbnailImages
{
    public delegate void DelegateStart();
    public delegate void DelegateDoException(Exception ex);
    public delegate void DelegateThreadFinished(string message);
    public delegate void DelegateProgressBarPerformStep(int fileIndex, string filename);

    public partial class frmMain : Form
    {
        int width = 600, height = 600;
        int percent = -1;
        int totalFileCount = 0;
        private Thread timedProgress;
        string sourcePath, targetPath;
        string[] files;

        public DelegateStart DelegateStart;
        public DelegateDoException DelegateDoException;
        public DelegateThreadFinished DelegateThreadFinished;
        public DelegateProgressBarPerformStep DelegateProgressBarPerformStep;

        public frmMain()
        {
            InitializeComponent();
            this.cbDefined.SelectedIndex = 2;

            DelegateStart = new DelegateStart(this.Start);
            DelegateThreadFinished = new DelegateThreadFinished(this.ThreadFinished);
            DelegateDoException = new DelegateDoException(this.DoException);
            DelegateProgressBarPerformStep = new DelegateProgressBarPerformStep(this.ProgressBarPerformStep);

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string sourcePath = txtSource.Text;
            string targetPath = txtTarget.Text;
            if (sourcePath.Length == 0 || !Directory.Exists(sourcePath))
            {
                txtSource.Focus();
                MessageBox.Show("请重新选择图片文件夹!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (targetPath.Length == 0)
            {
                txtTarget.Focus();
                MessageBox.Show("请重新选择图片保存路径!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!Directory.Exists(targetPath))
            {
                try
                {
                    Directory.CreateDirectory(targetPath);
                }
                catch
                {
                    txtTarget.Focus();
                    MessageBox.Show("请重新选择图片保存路径!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            GetImageSizeSetting();

            timedProgress = new Thread(new ThreadStart(TimedProgressProc));
            timedProgress.IsBackground = true;
            timedProgress.Start();

        }

        public void Start()
        {
            sourcePath = txtSource.Text;
            targetPath = txtTarget.Text;
            files = Directory.GetFiles(sourcePath);
            totalFileCount = files.Length;
            this.lblInfo.Text = string.Format("0/{0}", totalFileCount);
            this.progressBar.Maximum = totalFileCount;
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;

        }

        public void ThreadFinished(string message)
        {
            if (MessageBox.Show(message, "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(targetPath);
            }
           
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            this.progressBar.Value = 0;
            this.lblInfo.Text = "全部完成!";
        }
        public void DoException(Exception ex)
        {
            MessageBox.Show(ex.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            this.progressBar.Value = 0;
        }
        public void ProgressBarPerformStep(int fileIndex, string filename)
        {
            progressBar.PerformStep();
            filename = Path.GetFileName(filename);
            this.lblInfo.Text = string.Format("{0}/{1}, 当前文件: {2}", fileIndex, totalFileCount, filename);
        }

        private void TimedProgressProc()
        {
            try
            {
                ImageCodecInfo icf = ImageHelper.GetImageCodecInfo(ImageFormat.Jpeg);

                Image image, thumbnailImage;
                string thumbnailImageFilename;
                this.Invoke(this.DelegateStart);
                int i = 0;
                foreach (string filename in files)
                {
                    if (timedProgress == null)
                        return;
                    //lblInfo.Text = string.Format("正在处理: {0} ", filename); ;
                    progressBar.Invoke(this.DelegateProgressBarPerformStep, new object[] { i++, filename });
                    string extension = Path.GetExtension(filename).ToLower();
                    if (extension != ".jpg"
                        && extension != ".jpeg"
                        && extension != ".gif"
                        && extension != ".bmp"
                        && extension != ".png"
                        )
                        continue;
                    try
                    {
                        using (image = Image.FromFile(filename))
                        {
                            Size imageSize = GetImageSize(image);

                            using (thumbnailImage = ImageHelper.GetThumbnailImage(image, imageSize.Width, imageSize.Height))
                            {
                                //thumbnailImageFilename = Path.GetFileNameWithoutExtension(filename) + "_" + thumbnailImage.Width + "x" + thumbnailImage.Height + extension;
                                thumbnailImageFilename = Path.GetFileNameWithoutExtension(filename) + extension;
                                ImageHelper.SaveImage(thumbnailImage, Path.Combine(targetPath, thumbnailImageFilename), icf);
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        string em = ex.Message;
                        //lblInfo.Text = string.Format("{0} 可能不是合法的图片文件!", filename);
                    }
                }
                this.Invoke(this.DelegateThreadFinished, new object[] { "已经全部完成!\n是否打开生成图片的所在文件夹?" });
            }
            catch (ThreadInterruptedException e)
            {
                return;
            }
            catch (Exception ex)
            {
                this.Invoke(this.DelegateDoException, new Object[] { ex });
            }

        }

        private Size GetImageSize(Image picture)
        {
            Size imageSize;
            if (percent > 0)
            {
                imageSize = new Size(picture.Width * percent / 100, picture.Height * percent / 100);
            }
            else
                imageSize = new Size(width, height);

            double heightRatio = (double)picture.Height / picture.Width;
            double widthRatio = (double)picture.Width / picture.Height;

            int desiredHeight = imageSize.Height;
            int desiredWidth = imageSize.Width;
            imageSize.Height = desiredHeight;
            if (widthRatio > 0)
                imageSize.Width = Convert.ToInt32(imageSize.Height * widthRatio);

            if (imageSize.Width > desiredWidth)
            {
                imageSize.Width = desiredWidth;
                imageSize.Height = Convert.ToInt32(imageSize.Width * heightRatio);
            }

            if (checkSmart.Checked == true)
            {
                if (picture.Width < imageSize.Width && picture.Height < imageSize.Height)
                {
                    imageSize.Width = picture.Width;
                    imageSize.Height = picture.Height;
                }
            }

            return imageSize;
        }

        private void GetImageSizeSetting()
        {
            if (rbDefined.Checked)
            {
                if (cbDefined.SelectedIndex == 0)
                {
                    width = 550;
                    height = 550;
                }
                else if (cbDefined.SelectedIndex == 1)
                {
                    width = 130;
                    height = 130;
                }
                else if (cbDefined.SelectedIndex == 2)
                {
                    width = 600;
                    height = 600;
                }
                else if (cbDefined.SelectedIndex == 3)
                {
                    width = 150;
                    height = 150;
                }
            }
            else if (rbCustom.Checked)
            {
                width = (int)numWidth.Value;
                height = (int)numHeight.Value;
            }
            else if (rbDefined.Checked)
            {
                percent = (int)numPercent.Value;
            }
        }

        private void cbDefined_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!rbDefined.Checked)
                rbDefined.Checked = true;
        }

        private void btnBrowserSource_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtSource.Text = folderBrowserDialog.SelectedPath;
                //if (txtTarget.Text.Length == 0)
                txtTarget.Text = Path.Combine(folderBrowserDialog.SelectedPath, "_处理后的图片");
            }
        }

        private void btnBrowserTarget_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtTarget.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start(http://www.phpker.com);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (timedProgress != null)
            {
                timedProgress.Interrupt();
                timedProgress = null;
                ThreadFinished("已经取消!\n是否打开生成图片的所在文件夹?");
                this.lblInfo.Text = "已取消!";
            }
        }
    }
}

正则表达式口诀及教程

正则其实也势利,削尖头来把钱揣; (指开始符号^和结尾符号$)
特殊符号认不了,弄个倒杠来引路; (指\. \*等特殊符号)
倒杠后面跟小w, 数字字母来表示; (\w跟数字字母;\d跟数字)
倒杠后面跟小d, 只有数字来表示;
倒杠后面跟小a, 报警符号嘀一声;
倒杠后面跟小b, 单词分界或退格;
倒杠后面跟小t, 制表符号很明了;
倒杠后面跟小r, 回车符号知道了;
倒杠后面跟小s, 空格符号很重要;
小写跟罢跟大写,多得实在不得了;
倒杠后面跟大W, 字母数字靠边站;
倒杠后面跟大S, 空白也就靠边站;
倒杠后面跟大D, 数字从此靠边站;
倒框后面跟大B, 不含开头和结尾;

单个字符要重复,三个符号来帮忙; (* + ?)
0 星加1 到无穷,问号只管0 和1; (*表0-n;+表1-n;?表0-1次重复)
花括号里学问多,重复操作能力强; ({n} {n,} {n,m})
若要重复字符串,园括把它括起来; ((abc){3} 表示字符串“abc”重复3次 )
特殊集合自定义,中括号来帮你忙;
转义符号行不通,一个一个来排队;
实在多得排不下,横杠请来帮个忙; ([1-5])
尖头放进中括号,反义定义威力大; ([^a]指除“a”外的任意字符 )
1竖作用可不小,两边正则互替换; (键盘上与“\”是同一个键)
1竖能用很多次,复杂定义很方便;
园括号,用途多;
反向引用指定组,数字排符对应它; (“\b(\w+)\b\s+\1\b”中的数字“1”引用前面的“(\w+)”)
支持组名自定义,问号加上尖括号; (“(?<Word>\w+)”中把“\w+”定义为组,组名为“Word”)
园括号,用途多,位置指定全靠它;
问号等号字符串,定位字符串前面; (“\b\w+(?=ing\b)”定位“ing”前面的字符串)
若要定位串后面,中间插个小于号; (“(?<=\bsub)\w+\b”定位“sub”后面的字符串)
问号加个惊叹号,后面跟串字符串;
PHPer都知道, !是取反的意思;
后面不跟这一串,统统符合来报到; (“\w*d(?!og)\w*”,“dog”不符合,“do”符合)
问号小于惊叹号,后面跟串字符串;
前面不放这一串,统统符合来报到;
点号星号很贪婪,加个问号不贪婪;
加号问号有保底,至少重复一次多;
两个问号老规矩,0次1次团团转;
花括号后跟个?,贪婪变成不贪婪;
还有很多装不下,等着以后来增加