C#编程积累

1.带有命名空间的xml解析

 XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);

            XmlElement root = doc.DocumentElement;
            string nameSpace = root.NamespaceURI;
            XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
            xnm.AddNamespace("ns", nameSpace);

            doc.SelectNodes("ns:Window/ns:Grid", xnm);


2.List等集合排序的委托比较方法

 private static int CompareDinosByLength(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the 
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }

3.程序只让运行一个实例

public static Process GetRunningInstance()
{
    Process current = Process.GetCurrentProcess();
    Process[] processes = Process.GetProcessesByName(current.ProcessName);
    //查找相同名称的进程   
    foreach (Process process in processes)
    {
        //忽略当前进程   
        if (process.Id != current.Id)
        {
            //确认相同进程的程序运行位置是否一样.   
            if (Assembly.GetExecutingAssembly().Location.Replace("/ ", "\\ ") == current.MainModule.FileName)
            {
                //Return   the   other   process   instance.   
                return process;
            }
        }
    }
    //No   other   instance   was   found,   return   null.   
    return null;
}  


  if (process == null)
 {
       Application.Run(new FrmLogin());
 }


MD5加密

public static class CryptoHelper
{
    /// <summary>
    /// 从文件产生MD5校验码
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string GetMD5CodeFromFile(string filePath)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        FileStream fst = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);
        md5.ComputeHash(fst);
        byte[] hash = md5.Hash;
        string aMD5Code = System.BitConverter.ToString(hash).Replace("-", "");


        fst.Close();
        fst.Dispose();
        return aMD5Code;
    }


    /// <summary>
    /// 从字符串生成md5
    /// </summary>
    /// <param name="aStr"></param>
    /// <returns></returns>
    public static string GetMD5CodeFromString(string aStr)
    {
        string aMD5Code = "";
        MD5CryptoServiceProvider aMD5CSP = new MD5CryptoServiceProvider();
        //注意:这里选择的编码不同 所计算出来的MD5值也不同例如
        Byte[] aHashTable = aMD5CSP.ComputeHash(Encoding.ASCII.GetBytes(aStr));
        aMD5Code = System.BitConverter.ToString(aHashTable).Replace("-", "");
        return aMD5Code;
    }
}


C#的Json使用

添加System.Runtime.Serialization.dll引用

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

[DataContract(Namespace = "http://www.google.com.hk")]
public class Config
{
    [DataMember(Order = 0)]
    public string encoding { get; set; }
    [DataMember(Order = 1)]
    public string[] plugins { get; set; }
 
}

var config = new Config()
{
    encoding = "UTF-8",
    plugins = new string[] { "python", "C++", "C#" }
};
List<Config> list = new List<Config>();
for (int i = 0; i < 2; i++)
{
    list.Add(config); 
}
var serializer = new DataContractJsonSerializer(typeof(List<Config>));
FileStream fs=  File.OpenWrite("c:\\1.txt");
serializer.WriteObject(fs, list );
fs.Close();
 
FileStream reader = File.Open("c:\\1.txt",FileMode.Open);
object obj= serializer.ReadObject(reader);
List<Config> newlist = obj as List<Config>;
reader.Close();


计算字符串长度

 Graphics g = this.CreateGraphics();
SizeF sizeF = g.MeasureString("abc", this.Font);


fastJSON使用

public static class MyFastJsonParser
{
    /// <summary>
    /// 解析fastJSON的json数组ArrayList
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array">fastJSON的json数组</param>
    /// <param name="list">返回List对象数组</param>
    public static void ParseJsonArray<T>(ArrayList array, ref List<T> list) where T : new()
    {
        list.Clear();
        PropertyInfo[] propertyList = typeof(T).GetProperties();

        //获取对象所有属性
        Dictionary<string, PropertyInfo> propertyDic = new Dictionary<string, System.Reflection.PropertyInfo>();
        foreach (var item in propertyList)
        {
            propertyDic.Add(item.Name, item);
        }

        for (int i = 0; i < array.Count; i++)
        {
            Dictionary<string, object> dic = array[i] as Dictionary<string, object>;
            if (dic == null) continue;

            T item = new T();
            //复制值
            foreach (var key in dic.Keys)
            {
                if (propertyDic.ContainsKey(key))
                {
                    PropertyInfo propertyInfo = propertyDic[key];
                    if (!propertyInfo.CanWrite) continue;//跳过不可写元素
                    propertyInfo.SetValue(item, dic[key], null);
                }
            }
            list.Add(item);
        }
    }

    /// <summary>
    /// 解析fastJSON字符串
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonStr"></param>
    /// <param name="list"></param>
    public static void Parse<T>(string jsonStr, ref List<T> list) where T : new()
    {
        object obj = fastJSON.JSON.Instance.Parse(jsonStr);
        ArrayList arayList = (ArrayList)obj;
        ParseJsonArray<T>(arayList, ref list);
    }
    /// <summary>
    /// 转成fastJSON字符串
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToJsonString<T>(object obj)
    {
        return fastJSON.JSON.Instance.ToJSON(obj);
    }
}


中文编码

System.Text.Encoding.GetEncoding("GB18030") //这个编码可以解析几乎所有中文


控件屏蔽Enter,Tab等其他键

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.Enter)
    {
        return false;
    }
    return base.ProcessDialogKey(keyData);
}

来自msdn的说明:

This method is called during message preprocessing to handle dialog characters, such as TAB, RETURN, ESC, and arrow keys. This method is called only if the IsInputKey method indicates that the control is not processing the key. The ProcessDialogKey simply sends the character to the parent's ProcessDialogKey method, or returns false if the control has no parent. The Form class overrides this method to perform actual processing of dialog keys. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.


控制文本录入框输入内容

  private void TextBox_Age_TextChanged(object sender, EventArgs e)
        {
            //增加列,修改这里
            TextBox editingControl = sender as TextBox;
            if (editingControl == null) return;

            //记录原来光标位置
            int originCaretPos = editingControl.SelectionStart;

            string newStr = ToolHelper.ConvertToString(editingControl.Text);

            //转半角
            newStr = ToolHelper.ToDBC(newStr);

            //去除特殊字符
            newStr = ToolHelper.FilterSpecialChars(newStr);

            //去除首尾空格
            newStr = newStr.Trim();
            newStr = BizHelper.RemoveUnDigitChars(newStr);
            editingControl.Text = newStr;

            // 设置光标位置到文本最后 
            editingControl.SelectionStart = originCaretPos;//editingControl.TextLength;
            // 随文本滚动 
            editingControl.ScrollToCaret();
        }


读取xml文件

XmlDocument doc = new XmlDocument();
doc.Load(appConfigFile);
XmlElement root = doc.DocumentElement;
XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
string xpathStr = "/configuration/system.serviceModel/client/endpoint";
XmlNodeList list = doc.SelectNodes(xpathStr, xnm);


线程安全自增

Interlocked.Increment(ref safeInstanceCount);

Interlocked.Decrement(ref safeInstanceCount);


递归删除文件

public static int DeleteDirRecursive(string aimPath)
{
    try
    {
        // 检查目标目录是否以目录分割字符结束如果不是则添加之
        if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
            aimPath += Path.DirectorySeparatorChar;
        // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
        // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
        // string[] fileList = Directory.GetFiles(aimPath);
        string[] fileList = Directory.GetFileSystemEntries(aimPath);
        // 遍历所有的文件和目录
        foreach (string file in fileList)
        {
            // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
            if (Directory.Exists(file))
            {
                DeleteDirRecursive(aimPath + Path.GetFileName(file));
            }
            // 否则直接Delete文件
            else
            {
                File.Delete(aimPath + Path.GetFileName(file));
            }
        }
        //删除文件夹
        System.IO.Directory.Delete(aimPath, true);
    }
    catch (Exception e)
    {
        return -1;
    }
    return 0;
}


创建桌面快捷方式

引入com库Windows Script Host Object Model

public static void CreateDesktopLnk(string exePath, string shortCutName)
{
    FileInfo fileInfo = new FileInfo(exePath); 
    string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹 
    IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();
    IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(DesktopPath + "\\" + shortCutName + ".lnk");
    shortcut.TargetPath = fileInfo.FullName;
    shortcut.Arguments = "";// 参数 
    shortcut.Description = shortCutName;
    shortcut.WorkingDirectory = fileInfo.Directory.FullName;//程序所在文件夹,在快捷方式图标点击右键可以看到此属性 
    string iconPath = fileInfo.Directory.FullName + Path.DirectorySeparatorChar + "icons"+Path.DirectorySeparatorChar +"folder.ico";
    shortcut.IconLocation = string.Format(@"{0},0", iconPath);//图标 
    shortcut.Hotkey = "";// "CTRL+SHIFT+Z";//热键 
    shortcut.WindowStyle = 1;
    shortcut.Save();

}


运行cmd命令

/// <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;
}

string[] cmd = new string[] { string.Format("attrib +r \"{0}\"", file) };
ToolHelper.Cmd(cmd);
ToolHelper.CloseProcess("cmd.exe");

你可能感兴趣的:(C#编程积累)