没时间写博客了。。欢迎大家转到我的微薄http://weibo.com/xsi64/
MD5是一种常用的加密算法,是不可逆的。经常用在登录密码的加密等。下面给出两种加密算法,很简单,直接看代码。
/// <summary>
/// MD5 16位加密算法
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static string ConvertMd5By16Bit(string source)
{
MD5 md5 = MD5.Create();
byte[] bs = Encoding.UTF8.GetBytes(source);
bs = md5.ComputeHash(bs);
return BitConverter.ToString(bs, 4, 8).Replace("-", "").ToLower();
}
/// <summary>
/// MD5 32位加密算法
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static string ConvertMd5By32Bit(string source)
{
MD5 md5 = MD5.Create();
byte[] bs = Encoding.UTF8.GetBytes(source);
bs = md5.ComputeHash(bs);
return BitConverter.ToString(bs).Replace("-", "").ToLower();
}
我们知道在IE、火狐浏览器中点击某个按钮复制一段文本,有时会有弹出提示或不起作用的时候,今天,我们就来解决这个问题。
原理:借助Flash的力量,将内容复制到剪贴板。
由于本人不会Flash就在网上找到了一个类库,帮我们完成这个操作。Zero Clipboard
先看一下最后实现的效果。
代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>New Document </title>
<script type="text/javascript" src="ZeroClipboard.js"></script>
<script type="text/javascript">
window.onload = function () {
//创建ZeroClipboard对象
var clip = new ZeroClipboard.Client();
//设置鼠标停留在复制按钮上是手型
clip.setHandCursor(true);
//鼠标按下时,复制到剪贴板。。。ps:很费解,为什么不是click非是mouseOver
clip.addEventListener('mouseOver', function (client) {
clip.setText(document.getElementById('inputText').value);
});
//设置复制到剪贴板完成时,输出
clip.addEventListener('complete', function (client, text) {
alert("复制成功!:\n" + text);
});
//设置按钮的Dom对象
clip.glue('btnCopy');
}
</script>
</head>
<body>
<div id="flash_copy"></div>
<input type="text" id="inputText" />
<input type="button" value="复制到剪贴板" id="btnCopy" />
</body>
</html>
具体说明,直接看注释吧。代码下载
就是使用HttpWebRequest和HttpWebResponse两个对象下载文件,很容易看懂。
/// <summary>
/// 下载文件并保存到本地目录。
/// </summary>
/// <param name="url"></param>
/// <param name="localPath"></param>
/// <param name="webProxy"></param>
/// <returns></returns>
public static bool DownloadFile(string url, string localPath, IWebProxy webProxy)
{
bool flag = false;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
req.Proxy = webProxy;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
long totalBytes = resp.ContentLength;
using (Stream sResp = resp.GetResponseStream())
{
if (!Directory.Exists(localPath.Substring(0, localPath.LastIndexOf('\\'))))
{
Directory.CreateDirectory(localPath.Substring(0, localPath.LastIndexOf('\\')));
}
using (Stream sFile = new FileStream(localPath, FileMode.Create))
{
long totalDownloadBytes = 0;
byte[] bs = new byte[1024];
for (int size = sResp.Read(bs, 0, bs.Length); size > 0; size = sResp.Read(bs, 0, bs.Length))
{
totalDownloadBytes += size;
sFile.Write(bs, 0, size);
}
}
}
flag = true;
}
catch (Exception ex)
{
throw ex;
}
return flag;
}
废话不说了,大家直接看代码就明白了。
using (EventLog log = new EventLog()) //初始化EventLog实例
{
log.Source = ".Net开发者"; //设置日志的来源
log.Log = ".Net开发者"; //设置日志的名称
//写入日志
log.WriteEntry("欢迎光临 .Net开发者!", //日志内容
EventLogEntryType.Information); //日志级别
}
事件查看器结果:
这样,我们可以很方便的将我们的应用程序日志加到系统中,方便管理和查看
C#使用SharpZipLib类库压缩、解压缩单个文件,废话不说了,直接看代码吧,
类库下载地址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
/// <summary>
/// 使用SharpZipLib压缩Zip文件
/// </summary>
/// <param name="srcFile">源文件</param>
/// <param name="dstFile">压缩后的Zip文件</param>
/// <param name="bufferSize">缓冲大小</param>
public static void Zip(string srcFile, string dstFile, int bufferSize)
{
using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
{
using (FileStream fileStreamOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write))
{
using (ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut))
{
byte[] buffer = new byte[bufferSize];
ZipEntry entry = new ZipEntry(Path.GetFileName(srcFile));
zipOutStream.PutNextEntry(entry);
int size;
do
{
size = fileStreamIn.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
zipOutStream.Flush();
}
}
}
}
/// <summary>
/// 使用SharpZipLib解压缩Zip文件
/// </summary>
/// <param name="srcFile">Zip源文件</param>
/// <param name="dstFile">解压出来的文件</param>
/// <param name="bufferSize">缓冲大小</param>
public static void UnZip(string srcFile, string dstFile, int bufferSize)
{
using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
{
using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn))
{
ZipEntry entry = zipInStream.GetNextEntry();
using (FileStream fileStreamOut = new FileStream(dstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write))
{
int size;
byte[] buffer = new byte[bufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Flush();
}
}
}
}
/// <summary>
/// 测试Zip文件是否完整
/// </summary>
/// <param name="srcFile">Zip源文件</param>
/// <returns></returns>
public static bool Test(string srcFile)
{
bool flag = false;
using (ZipFile zf = new ZipFile(srcFile))
{
flag = zf.TestArchive(true);
}
return flag;
}
.Net提供了一个叫Lazy<T>的对象,可以让我们很方便的延时创建大型或消耗资源的对象,可以很好的提高应用程序的性能。
如何实现呢?看下面代码:
class Program
{
static void Main(string[] args)
{
Lazy<Test> lazy = new Lazy<Test>(); //封装要延时加载的对象
Console.WriteLine("创建Lazy对象");
Console.WriteLine("是否创建对象:" + lazy.IsValueCreated);
lazy.Value.Run(); //调用对象中的方法
}
}
public class Test
{
public Test()
{
Console.WriteLine("创建Test对象");
}
public void Run()
{
Console.WriteLine("跑!");
}
}
运行结果:
默认设置下,这个类的所有成员都是线程安全的。我们可以很方便的使用这个类实现对某个对象的延迟加载。
扩展方法让大家很容易的向现有类型中添加方法(不破坏源类的内容)。
写法,看代码:
class Program
{
static void Main(string[] args)
{
Human human = new Human();
human.Name = "张三";
human.Age = 18;
human.GetName();
human.GetAge("岁");
}
}
public class Human
{
public string Name { get; set; }
public int Age { get; set; }
}
public static class HumanExtension
{
/// <summary>
/// 扩展Human类的方法GetName
/// </summary>
/// <param name="human"></param>
public static void GetName(this Human human)
{
Console.WriteLine("姓名:" + human.Name);
}
/// <summary>
/// 扩展Human类的方法GetAge
/// </summary>
/// <param name="human"></param>
/// <param name="unit">单位</param>
public static void GetAge(this Human human, string unit)
{
Console.WriteLine("年龄:" + human.Age + unit);
}
}
很容易吧,需要注意的是,扩展方法必须是在非泛型静态类中定义,并且扩展方法必须是静态的,方法的第一个参数必须是this [类型]。使用扩展方法,可以很容易的为我们已有的类添加方法,如给String类添加个ToSource方法等。
大家都经常发送电子邮件,但是,如何使用C#来发送电子邮件呢?直接看下面代码吧,注释写的很清楚了。
MailMessage mail = new MailMessage();
//收件人电子邮件地址
mail.To.Add("xsi64@126.com");
//发件人电子邮件地址
mail.From = new MailAddress("xsi64@gmail.com");
//电子邮件主题
mail.Subject = "测试发送电子邮件";
//电子邮件内容
mail.Body = "欢迎光临<a href='http://www.dotnetdev.cn'>.Net开发者Blog</a>!";
//邮件内容支持HTML
mail.IsBodyHtml = true;
//向邮件内容中添加一个图片标签,制定id为"image1"
mail.Body += "<br/><img alt=\"\" src=\"cid:image1\">";
//new一个电子邮件嵌入资源对象,路径是F:\test.jpg
LinkedResource imgLink = new LinkedResource(@"F:\test.jpg");
//将该附件id设为image1,
imgLink.ContentId = "image1";
//该资源对象传输编码设为Base64
imgLink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
//创建一个电子邮件查看格式为"text/html"
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mail.Body, null, "text/html");
//将嵌入内容的图片附件,放入嵌入资源集
htmlView.LinkedResources.Add(imgLink);
//放入电子邮件内容中
mail.AlternateViews.Add(htmlView);
//向电子邮件中,添加一个附件,路径为"f:\test.txt"
mail.Attachments.Add(new Attachment(@"F:\test.txt"));
//新建一个smtpClient
SmtpClient smtp = new SmtpClient();
//设置smtp服务器地址
smtp.Host = "smtp.xxx.com";
//设置smtp服务器认证方式
smtp.Credentials = new NetworkCredential("xxx登录名", "xxx登陆密码");
//设置stmp服务器是否启用了ssl加密
smtp.EnableSsl = true;
//发送该邮件
smtp.Send(mail);
比如,如果我们已知扩展名,如何获得该扩展名的默认系统图标呢?我们只要使用下面Win32函数就可以获得该图标的句柄,然后,再通过句柄获得图像文件。
[DllImport("Shell32")]
extern static IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, out SHFILEINFO psfi, int cbFileInfo, FileInfoFlags uFlags);


