C#的一些小技术 <1>

来源:互联网 发布:javascript 服务端 编辑:程序博客网 时间:2024/05/16 13:57

一些C#的小技术,代码部分不考虑执行效率,只为分享一些思路。

1.对字符串进行大小写切换:

 public class Program 
 {
     public static void Main() 
     { 
         string s = "OsChInAhI§$%&/()1234567890"; 
         Func<char, char> toggle = c => char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); 
         Console.WriteLine(s); 
         Console.WriteLine(new string(s.Select(toggle).ToArray())); 
     } 
 }
2.equals与==的区别

    对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false。对于string 以外的引用类型,如果两个对象引用同一个对象,则 == 返回 true。对于 string 类型,== 比较字符串的值。
    ==操作比较的是两个变量的值是否相等。
    equals()方法比较的是两个对象的内容是否一致.equals也就是比较引用类型是否是对同一个对象的引用。

3.IP地址转换

             string ipAddress ="192.128.128.128";
             string[] ary= ipAddress.Split('.');
             UInt32 ipNumber = 0;
             for(int i=0;i<4;i++)
             {
                ipNumber += UInt32.Parse(ary[i]) << (3 - i) * 8;
                Console.WriteLine("ipAddress to Number:"+ipNumber);
             }
             Console.WriteLine("ipAddress to Number:"+ipNumber);

             string[] ipAry = new string[4];
             UInt32 temp = ipNumber;

             for (int i = 3; i >= 0; i--)
             {
                ipAry [3-i]= (temp >> (i * 8)).ToString();
                temp -= (temp >> (i * 8))<<(i*8);
                Console.WriteLine(ipAry[3-i]);
             }
             Console.WriteLine(string.Join(".", ipAry)); 
             Console.Read();

4.与剪切板的数据交换

发送数据到剪贴板

using System.Windows.Forms;
Clipboard.SetText("test");

从剪贴板中取数据

using   System.Windows.Forms;
IDataObject   iData = Clipboard.GetDataObject();
   if(iData.GetDataPresent(DataFormats.Text))
 {
    MessageBox.Show((string)iData.GetData(DataFormats.Text));
 }
 else
      MessageBox.Show("目前剪贴板中数据不可转换为文本","错误");
 

5.一个对称加密、解密的方法

 封装了一个对称加解密的类,用私钥和密钥加解密

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Security.Cryptography;

namespace CMD.EDI

{

    public classEncryptHandler

    {

        /// <summary>

        /// 加密字符串

        /// </summary>

        public static stringEncrypt(string password, string cleartext)

        {

            string password2 ="Ahbool";

            string cipher;

            char[] key = newchar[8];

            if(password.Length > 8)

            {

                password =password.Remove(8);

            }

            password.CopyTo(0,key, 0, password.Length);

            char[] iv = newchar[8];

            if(password2.Length > 8)

            {

                password2 = password2.Remove(8);

            }

           password2.CopyTo(0, iv, 0, password2.Length);

            if (cleartext ==null)

            {

                returnstring.Empty;

            }

            SymmetricAlgorithmserviceProvider = new DESCryptoServiceProvider();

           serviceProvider.Key = Encoding.ASCII.GetBytes(key);

            serviceProvider.IV= Encoding.ASCII.GetBytes(iv);

            MemoryStream memoryStream= new MemoryStream();

            CryptoStreamcryptoStream = new CryptoStream(memoryStream,serviceProvider.CreateEncryptor(), CryptoStreamMode.Write);

            StreamWriterstreamWriter = new StreamWriter(cryptoStream);

           streamWriter.Write(cleartext);

           streamWriter.Dispose();

           cryptoStream.Dispose();

            byte[] signData =memoryStream.ToArray();

           memoryStream.Dispose();

            serviceProvider.Clear();

            cipher =Convert.ToBase64String(signData);

            return cipher;

        }

        /// <summary>

        /// 解密字符串

        /// </summary>

        public static stringDecrypt(string password, string ciphertext)

        {

            string password2 ="Ahbool";

            string cipher =string.Empty;

            try

            {

                char[] key =new char[8];

                if(password.Length > 8)

                {

                    password =password.Remove(8);

                }

               password.CopyTo(0, key, 0, password.Length);

                char[] iv =new char[8];

                if(password2.Length > 8)

                {

                    password2= password2.Remove(8);

                }

               password2.CopyTo(0, iv, 0, password2.Length);

                if (ciphertext== null)

                {

                    returncipher;

                }

               SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();

               serviceProvider.Key = Encoding.ASCII.GetBytes(key);

               serviceProvider.IV = Encoding.ASCII.GetBytes(iv);

                byte[]contentArray = Convert.FromBase64String(ciphertext);

                MemoryStreammemoryStream = new MemoryStream(contentArray);

                CryptoStreamcryptoStream = new CryptoStream(memoryStream,serviceProvider.CreateDecryptor(), CryptoStreamMode.Read);

                StreamReaderstreamReader = new StreamReader(cryptoStream);

                cipher =streamReader.ReadToEnd();

               streamReader.Dispose();

               cryptoStream.Dispose();

               memoryStream.Dispose();

               serviceProvider.Clear();

            }

            catch (Exceptionex)

            {

                throw newSystemException("密钥错误,数据包解密失败.");

            }

            return cipher;

        }

    }

}

6.十进制或十六进制字符串加1

简单的字符串加1程序,当你想让流水号自动加1的时候可以做个参考

namespace Test

{

   public partial class frmMain : Form

    {

       public frmMain()

       {

            InitializeComponent();

       }

      private int Asc(string character)

       {

           if (character.Length == 1)

           {

                System.Text.ASCIIEncodingasciiEncoding = newSystem.Text.ASCIIEncoding();

                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];

               return (intAsciiCode);

           }

           else

           {

                throw new Exception("Characteris not valid.");

           }

       }

       private string Chr(int asciiCode)

       {

           if (asciiCode >= 0 && asciiCode <= 255)

           {

                System.Text.ASCIIEncodingasciiEncoding = newSystem.Text.ASCIIEncoding();

                byte[] byteArray = new byte[] {(byte)asciiCode };

                string strCharacter = asciiEncoding.GetString(byteArray);

               return (strCharacter);

           }

           else

           {

                throw new Exception("ASCIICode is not valid.");

            }

       }

       private string strinc(string s1, int hex)

       {

           string str,newstr;

           int index = 0;

           int newInt;

           str = s1.Trim().Replace(" ", "");

            str = str.ToUpper();

           if (hex == 10)

           {

                for (int i = str.Length - 1; i> 0; i--)

                {

                   if (str[i] != (char)57)

                    {

                        index = i;

                        break;

                    }

                }

                newInt = Convert.ToInt32(str.Substring(index))+ 1;

                str = str.Substring(0, index) +newInt.ToString();

           }

           else if (hex == 16)

           {

                newstr = "";

                for (int i = str.Length - 1; i> 0; i--)

                {

                   if (str[i] == (char)57)

                    {

                       newstr ="A";

                        index = i;

                        break;

                    }

                    else if (str[i] != (char)70)

                    {

                        newstr =Chr(Asc(str.Substring(i, 1)) + 1);

       index = i;

                        break;

                    }

                }

                str = str.Substring(0, index) +newstr+str.Substring(index+1).Replace("F","0");  

           }

           return str;

    }

       private void button1_Click_1(object sender, EventArgs e)

       {

          textbox1.Text = strinc(textbox1.Text, 10);    //10进制加1

        //textbox1.Text = strinc(textbox1.Text, 16);    //16进制加1

       }

}


      继续整理整理中……

 

原创粉丝点击