您的位置:首页 > 编程语言 > C#

Visual C# 2005编程技巧大全

2007-09-07 20:41 169 查看
【书名 】:Visual C# 2005编程技巧大全
【评价 】:★★★★★☆☆☆☆☆
【正文 】:
----------------------------------------------------------------------------------------------------
0001:
系统目录:string dir = Environment.GetEnvironmentVariable("WinDir");
----------------------------------------------------------------------------------------------------
0002:
使用字符绘制表格:
string msg = "┌────────────────────┐/n" +
"│世界你好 │/n" +
"└────────────────────┘/n";
----------------------------------------------------------------------------------------------------
0003:
反转字符串:
public static string Reverse(string str)
{
char[] chars = str.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
----------------------------------------------------------------------------------------------------
0004:
计算距离某一天的天数:
public static int Distance(DateTime dtTarget)
{
DateTime dtCurrent = DateTime.Now;
TimeSpan aTimeSpan = dtTarget.Subtract(dtCurrent);
return Convert.ToInt32(Math.Round(aTimeSpan.TotalDays,0));
}
----------------------------------------------------------------------------------------------------
0005:
获得某一年的天数:
public static int GetDays(int year)
{
System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
return gc.GetDaysInYear(year);
}
----------------------------------------------------------------------------------------------------
0006:
获得某一年的某一个月的天数:
public static int GetDays(int year,int month)
{
System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
return gc.GetDaysInMonth(year, month);
}
----------------------------------------------------------------------------------------------------
0007:
判断某一年是不是闰年:DateTime.IsLeapYear(2006)
----------------------------------------------------------------------------------------------------
0008:
如何根据年份判断生肖:
public static string GetTwelveAnimal(int year)
{
string animal = "";
switch (year % 12)
{
case 4:
animal = "鼠";
break;
case 5:
animal = "牛";
break;
case 6:
animal = "虎";
break;
case 7:
animal = "兔";
break;
case 8:
animal = "龙";
break;
case 9:
animal = "蛇";
break;
case 10:
animal = "马";
break;
case 11:
animal = "羊";
break;
case 0:
animal = "猴";
break;
case 1:
animal = "鸡";
break;
case 2:
animal = "狗";
break;
case 3:
animal = "猪";
break;
}
return animal;
}
----------------------------------------------------------------------------------------------------
0009:
如何将小写金额转换成大写金额的形式:
public static string ConvertToChineseMoneyFormat(string money)
{
string outstr = "";
string[] scales = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾",
"佰", "仟", "兆", "拾", "佰", "仟" };
string[] bases = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
//计算小数点前面的部分
string temp1 = money.Substring(0, money.IndexOf("."));
for (int i = temp1.Length; i > 0; i--)
{
int count = Convert.ToInt16(temp1[temp1.Length - i]);
outstr += bases[count - 48];
outstr += scales[i + 1];
}
//计算小数点后面的部分
string temp2 = money.Substring(money.IndexOf(".") + 1 , money.Length - money.IndexOf(".") - 1);
for (int i = temp2.Length; i > 0; i--)
{
int count = Convert.ToInt16(temp2[temp2.Length - i]);
outstr += bases[count - 48];
outstr += scales[i - 1];
}
return outstr;
}
----------------------------------------------------------------------------------------------------
0010:
Hashtable的序列化和反序列化:
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("zhangsan","23");
HashtableData.InData(ht,@"C:/data.dat");

Hashtable httemp = HashtableData.OutData(@"C:/data.dat");
Console.WriteLine(httemp["zhangsan"]);
}
}
public static class HashtableData
{
public static void InData(Hashtable ht,string path)
{
System.IO.FileStream fs = new System.IO.FileStream(path,System.IO.FileMode.OpenOrCreate);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, ht);
fs.Close();
}

public static Hashtable OutData(string path)
{
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
Hashtable ht = (Hashtable)bf.Deserialize(fs);
fs.Close();
return ht;
}
}
----------------------------------------------------------------------------------------------------
0011:
字典(支持泛型,可以代替哈西表):
Dictionary<int, string> dy = new Dictionary<int, string>();
dy.Add(1, "张三");
dy.Add(2, "李四");
Console.WriteLine(dy[1]);
----------------------------------------------------------------------------------------------------
0012:
加密解密:
public static class DataHelper
{
public static string Encrypt(string data)
{
//注意iv的长度,必须和key中的密码长度相同
byte[] iv = { 0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};
string password = "12345678";
byte[] key = System.Text.Encoding.UTF8.GetBytes(password);
byte[] datas = System.Text.Encoding.UTF8.GetBytes(data);
System.Security.Cryptography.DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cs = new CryptoStream(ms,dsp.CreateEncryptor(iv,key),CryptoStreamMode.Write);
cs.Write(datas, 0, datas.Length);
cs.FlushFinalBlock();
string outData = Convert.ToBase64String(ms.ToArray());
cs.Close();
ms.Close();
return outData;
}

public static string Decrypt(string data)
{
byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
string password = "12345678";
byte[] key = System.Text.Encoding.UTF8.GetBytes(password);
byte[] datas = Convert.FromBase64String(data);
System.Security.Cryptography.DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cs = new CryptoStream(ms, dsp.CreateDecryptor(iv, key), CryptoStreamMode.Write);
cs.Write(datas, 0, datas.Length);
cs.FlushFinalBlock();
string outData = System.Text.Encoding.UTF8.GetString(ms.ToArray());
cs.Close();
ms.Close();
return outData;
}
}
----------------------------------------------------------------------------------------------------
0013:
读取XML文档的简单方法:
XML文件:注意utf-16,这样才能支持中文
<?xml version="1.0" encoding="utf-16" ?>
<Shop>
<Book>历史小说</Book>
<Book>123</Book>
<Book>das</Book>
</Shop>

代码部分:
class Program
{
static void Main(string[] args)
{
string[] datas = XMLHelper.GetDataByTagName(@"C:/data.xml","Book");
foreach (string str in datas)
{
Console.WriteLine(str);
}
}
}
public static class XMLHelper
{
public static string[] GetDataByTagName(string path, string tagname)
{
System.Xml.XmlDocument xd = new XmlDocument();
xd.Load(path);
System.Xml.XmlNodeList xnl = xd.GetElementsByTagName(tagname);
string[] datas = new string[xnl.Count];
for (int i = 0; i < xnl.Count; i++)
{
System.Xml.XmlNode xn = xnl[i];
datas[i] = xn.InnerText;
}
return datas;
}
}
----------------------------------------------------------------------------------------------------
0014:
使用XPath查询XML中的内容:
XML文件:同上

代码部分:
class Program
{
static void Main(string[] args)
{
string[] datas = XMLHelper.GetDataByXPath(@"C:/data.xml", "descendant::Shop/Book");
foreach (string str in datas)
{
Console.WriteLine(str);
}
}
}
public static class XMLHelper
{
public static string[] GetDataByXPath(string path, string xpathsql)
{
System.Xml.XPath.XPathDocument xd = new XPathDocument(path);
System.Xml.XPath.XPathNavigator xn = xd.CreateNavigator();
System.Xml.XPath.XPathExpression xe = xn.Compile(xpathsql);
System.Xml.XPath.XPathNodeIterator xni = xn.Select(xe);
string[] datas = new string[xni.Count];
int i = 0;
while (xni.MoveNext())
{
datas[i] = xni.Current.Value;
i++;
}
return datas;
}
}
----------------------------------------------------------------------------------------------------
0015:
专门的键值对数据类型:
System.Collections.Specialized.NameValueCollection nvc = new NameValueCollection();
nvc.Add("01", "张三");
nvc.Add("02", "李四");
Console.WriteLine(nvc["02"]);
----------------------------------------------------------------------------------------------------
0016:
支持排序的键值对数据类型:
SortedList sl = new SortedList();
sl.Add("02", "02");
sl.Add("04", "04");
sl.Add("03", "03");
sl.Add("01", "01");
System.Collections.IEnumerator ie = sl.GetEnumerator();
while (ie.MoveNext())
{
DictionaryEntry de = (DictionaryEntry)ie.Current;
Console.WriteLine(de.Value.ToString());
}
----------------------------------------------------------------------------------------------------
0017:
判断是不是数字:
string str = "10.10";
double num;
bool isNumber = double.TryParse(str, out num);
Console.WriteLine(isNumber);
----------------------------------------------------------------------------------------------------
0018:
访问资源文件:资源文件名Resource.resx
Resource.Name
----------------------------------------------------------------------------------------------------
0019:
如何判断指定的文件是不是已经存在:bool isExists = System.IO.File.Exists(@"C:/data.xml");
----------------------------------------------------------------------------------------------------
0020:
压缩解压:
public static class ZipHelper
{
public static void Zip(string pathIn,string pathOut)
{
System.IO.FileStream fsIn = new FileStream(pathIn,FileMode.Open,FileAccess.Read,FileShare.Read);
int l = Convert.ToInt32(fsIn.Length);
byte[] dataIn = new byte[l];
fsIn.Read(dataIn, 0, l);

System.IO.FileStream fsOut = new FileStream(pathOut, FileMode.OpenOrCreate, FileAccess.Write);
System.IO.Compression.GZipStream gs = new GZipStream(fsOut,CompressionMode.Compress,true);
gs.Write(dataIn, 0, l);

fsIn.Close();
gs.Close();
fsOut.Close();
}
public static void UnZip(string pathIn,string pathOut)
{
System.IO.FileStream fsIn = new FileStream(pathIn, FileMode.Open);
System.IO.Compression.GZipStream gs = new GZipStream(fsIn, CompressionMode.Decompress, true);
byte[] dataInHeader = new byte[4];
int position = (int)fsIn.Length - 4;
fsIn.Position = position;
fsIn.Read(dataInHeader, 0, 4);
fsIn.Position = 0;
int l = BitConverter.ToInt32(dataInHeader, 0);
byte[] dataIn = new byte[l + 100];
int offset = 0;
int total = 0;
while (true)
{
int iRead = gs.Read(dataIn,offset,100);
if (iRead == 0)
{
break;
}
offset += iRead;
total += iRead;
}
System.IO.FileStream fsOut = new FileStream(pathOut, FileMode.Create);
fsOut.Write(dataIn, 0, total);
fsOut.Flush();

fsIn.Close();
gs.Close();
fsOut.Close();
}
}
----------------------------------------------------------------------------------------------------
0021:
加密解密文件:
public static class FileHelper
{
public static void Encrypt(string pathIn, string pathOut, string password)
{
byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] key = System.Text.Encoding.UTF8.GetBytes(password);
System.IO.FileStream fs = new FileStream(pathIn,FileMode.Open,FileAccess.Read);
System.IO.FileStream outfs = new FileStream(pathOut, FileMode.OpenOrCreate, FileAccess.Write);
outfs.SetLength(0);
byte[] myBytes = new byte[100];
long myInLength = 0;
long myLength = fs.Length;
System.Security.Cryptography.DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
System.Security.Cryptography.CryptoStream cs = new CryptoStream(outfs,dsp.CreateEncryptor(key,iv),CryptoStreamMode.Write);
while (myInLength < myLength)
{
int myLen = fs.Read(myBytes,0,100);
cs.Write(myBytes,0,myLen);
myInLength += myLen;
}
cs.Close();
fs.Close();
outfs.Close();
}
public static void Decrypt(string pathIn, string pathOut, string password)
{
System.IO.FileStream fs = new FileStream(pathIn, FileMode.Open, FileAccess.Read);
System.IO.FileStream outfs = new FileStream(pathOut, FileMode.OpenOrCreate, FileAccess.Write);
outfs.SetLength(0);
long myLength = fs.Length;
long myInLength = 0;
byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] key = System.Text.Encoding.UTF8.GetBytes(password);
System.Security.Cryptography.DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
System.Security.Cryptography.CryptoStream cs = new CryptoStream(outfs, dsp.CreateDecryptor(key, iv), CryptoStreamMode.Write);
byte[] myBytes = new byte[100];
while (myInLength < myLength)
{
int myLen = fs.Read(myBytes, 0, 100);
cs.Write(myBytes, 0, myLen);
myInLength += myLen;
}
cs.Close();
fs.Close();
outfs.Close();
}
}
----------------------------------------------------------------------------------------------------
0022:
读取配置文件中的数据:
配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="Name" value="张三"/>
</appSettings>
</configuration>

代码部分:
System.Configuration.AppSettingsReader asr = new AppSettingsReader();
string Name = (string)asr.GetValue("Name",typeof(string));
----------------------------------------------------------------------------------------------------
0023:
使用隐藏字段保留值:
protected void Button1_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterHiddenField("TIME", System.DateTime.Now.ToLongTimeString());
}
protected void Button2_Click(object sender, EventArgs e)
{
this.Response.Write(this.Request.Form["TIME"]);
}
----------------------------------------------------------------------------------------------------
0024:
页面异常的统一处理:
protected void Page_Error(object sender, EventArgs e)
{
string msg = this.Request.Url.ToString() + "<br>" + this.Server.GetLastError().Message;
this.Response.Write(msg);
this.Server.ClearError();
}
----------------------------------------------------------------------------------------------------
0025:
如何在一个页面中嵌入另外一个HTML页面:
<body>
<!--#Include File="WebForm.htm"-->
<form id="form1" runat="server">

</form>
</body>
----------------------------------------------------------------------------------------------------
0026:
如何在一个页面中显示另外一个页面:
<body>
<form id="form1" runat="server">
<iframe src="WebForm.aspx" style="width:500px; height:400px"></iframe>
</form>
</body>
----------------------------------------------------------------------------------------------------
0027:
如何使用HttpContext传递页间数据:
WebForm1:
protected void Button1_Click(object sender, EventArgs e)
{
string data = "世界你好";
this.Context.Items.Add("DATA",data);
//不能使用this.Response.Redirect("WebForm1.aspx"),地址栏的URL不变
this.Server.Transfer("WebForm1.aspx");
}

WebForm2:
protected void Page_Load(object sender, EventArgs e)
{
this.Response.Write(this.Context.Items["DATA"].ToString());
}
----------------------------------------------------------------------------------------------------
0028:
如何全屏幕打开页面:
protected void Page_Load(object sender, EventArgs e)
{
this.Button1.Attributes.Add("OnClick","window.open(document.location,'big','fullscreen=yes');");
this.Button2.Attributes.Add("OnClick","window.close();");
}
----------------------------------------------------------------------------------------------------
0029:
获得当前Web应用程序的物理路径:string path = Server.MapPath("");
----------------------------------------------------------------------------------------------------
0030:
获取客户端的IP地址:string ip = this.Request.UserHostAddress;
----------------------------------------------------------------------------------------------------
0031:
如何读取Web.config中的数据:
Web.config文件:
<configuration>
<appSettings>
<add key="Name" value="张三"/>
</appSettings>
</configuration>

代码部分:ConfigurationManager.AppSettings["Name"]
----------------------------------------------------------------------------------------------------
0032:
MD5加密的数据:
string nameByMD5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("张三", "md5");
----------------------------------------------------------------------------------------------------
0033:
确定按钮的实现:
protected void Page_Load(object sender, EventArgs e)
{
string confirmFun = @"<script language='JavaScript'>" +
@"function ClickConfirm()" +
@"{" +
@" return confirm('确认执行么?')" +
@"}" +
@"</script>";
if (this.ClientScript.IsClientScriptBlockRegistered("confirmFun") == false)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(),"confirmFun", confirmFun);
}
this.Button1.Attributes.Add("OnClick", "return ClickConfirm()");
}

protected void Button1_Click(object sender, EventArgs e)
{
this.Response.Write(DateTime.Now.ToLongTimeString());
}
}
----------------------------------------------------------------------------------------------------
0034:
显示弹出提示窗口时还能显示页面的实现:
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = @"<script type='text/javascript'>"+
@"alert('你好!');"+
@"</script>";
}
----------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: