zoukankan      html  css  js  c++  java
  • C#的一些代码

    form读取配置文件

           /// <summary>
            /// 读取配置文件
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            /// 引用 port.BaudRate = int.Parse(GetConfig(string.Format("Com_{0}_BaudRate", index)));   port.ByteSize = byte.Parse(GetConfig(string.Format("Com_{0}_ByteSize", index)));
            private static string GetConfig(string key)
            {
                
                System.Configuration.AppSettingsReader config = new System.Configuration.AppSettingsReader();
                return config.GetValue(key, typeof(string)).ToString();
            }
    查看代码

    form遍历文件夹内的文件,返回DataTable表

            public DataTable File_data(string sSourcePath)
            {
    
                DataTable Filedata = new DataTable(); //实例化
                Filedata.Columns.Add("RelativePath", Type.GetType("System.String"));//添加列
                Filedata.Columns.Add("FullPath", Type.GetType("System.String"));//添加列
                 DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);//遍历文件夹
                FileInfo[] thefileInfo = theFolder.GetFiles("*.*", SearchOption.TopDirectoryOnly);//仅只搜目录下的文件
                foreach (FileInfo NextFile in thefileInfo)  //遍历文件
                    Filedata.Rows.Add(NextFile.Name,NextFile.FullName);//向表添加数据
                DirectoryInfo[] dirInfo = theFolder.GetDirectories(); //遍历子文件夹,返回当前目录的子目录
                foreach (DirectoryInfo NextFolder in dirInfo)//
                {
                    FileInfo[] fileInfo = NextFolder.GetFiles("*.*", SearchOption.AllDirectories);//搜子目录下的文件,功能找子目录下的文件
                    foreach (FileInfo NextFile in fileInfo)  //遍历文件
                        Filedata.Rows.Add(NextFile.Name, NextFile.FullName);//向表添加数据行
                }
                return Filedata;//返回值
             }
    查看代码

     调用

    DataTable dt = File_data(@"D:mywed");
    

    计算文件的hash值 

    internal string CalcFileHash(string FilePath)
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] hash;
                using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096))
                {
                    hash = md5.ComputeHash(fs);
                }
                return BitConverter.ToString(hash);
            }
    查看代码

     webBrowser控件显示网页

    this.webBrowser1.DocumentText = "<h1>测试</h1>";
    

     form全局异常捕获

           #region Constructor
            static FileTransmiter()
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            }
    
            static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                StreamWriter writer = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exec.log"), true, Encoding.Default);
                writer.Write("Time:");
                writer.Write(DateTime.Now.ToShortTimeString());
                writer.Write(". ");
                writer.WriteLine(e.ExceptionObject);
                writer.Dispose();
            }
             #endregion
    查看代码

     线程委托操作控件

            /// <summary>
            /// 声明委托
            /// </summary>
            /// <param name="add_lst"></param>
            public delegate void lstServeritms(string add_lst);
            /// <summary>
            /// 线程通过委托的方法写入控件
            /// </summary>
            /// <param name="add_lst">字符串"test"</param>
            private void lstServeritmsResult(string add_lst)
            {
                if (lstServer.InvokeRequired == true)//检查是否跨线程,然后将方法加入委托,调用委托
                {
                    lstServeritms set = new lstServeritms(lstServeritmsResult);//委托的方法参数应和SetCalResult一致
                    lstServer.Invoke(set, new object[] { add_lst }); //此方法第二参数用于传入方法,代替形参result
                }
                else
                {
                    lstServer.Items.Add(add_lst);
                }
    
            }
    查看代码

     DataTable修改更新数据库

    private OleDbConnection oCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;       Data Source=|DataDirectory|\db\data.mdb");
     DataTable dt = new DataTable();
                using (oCon)
                {
                    //先取出从数据库中取出Datatable
                    OleDbCommand sqlcmd = new OleDbCommand("select * from  code_cheat where id=" + int.Parse(id), oCon);
                    oCon.Open();
                    OleDbDataReader sqlReader = null;
                    sqlReader = sqlcmd.ExecuteReader();
                    dt.Load(sqlReader);
    
                    //修改一条记录
                    dt.Rows[0]["code_content"] = postDataText;//修改字段的值
    
                    //以下三行代码就是把上面更改的数据更新到数据库中
                    OleDbDataAdapter sda = new OleDbDataAdapter(sqlcmd);
                    OleDbCommandBuilder sqlcmdB = new OleDbCommandBuilder(sda);
                    sda.Update(dt);
                }
    查看代码

    dataGridView返回当前行单击行的值

     private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                int rowindex = e.RowIndex;
                string code_id = dataGridView1.Rows[rowindex].Cells[0].Value.ToString();
                       }
    查看代码

     查询ACCESS

    /// <summary>
    /// OleDb查询数据库返回内容
    /// </summary>
    /// <param name="sql_str"></param>
    /// <returns></returns>
    protected DataTable dlBind(string sql_str)
    {
        oCon.Open();
        OleDbCommand ps = new OleDbCommand(sql_str, oCon);
        DataTable dt = new DataTable();
        dt.Load(ps.ExecuteReader());
        oCon.Close();
        return dt;
     
    }
    View Code

    打开文件并读取内容,保存字符到文件

    /// <summary>
    ///  打开文件,反回字符串
    /// </summary>
    /// <param name="file_path">"SyntaxHighligher/com.html"</param>
    /// <returns></returns>
    private string openfiletext(string file_path)
    {
        StreamReader htmlreader = new StreamReader(file_path);
        return htmlreader.ReadToEnd();
     
    }
    /// <summary>
    /// 保存字符串到文件
    /// </summary>
    /// <param name="filetext"></param>
    /// <param name="file_path">"SyntaxHighligher/com.html"</param>
    private void writefiletext(string filetext,string file_path)
    {
        FileStream MyFileStream = new FileStream(file_path, FileMode.Create, FileAccess.Write);
        StreamWriter htmlWriter = new StreamWriter(MyFileStream, System.Text.Encoding.UTF8);
        htmlWriter.WriteLine(filetext);
        htmlWriter.Close();
        MyFileStream.Close();
         
    }
    View Code

    转换人民币大写

    public static string CmycurD(double num)
            {
                string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字
                string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
                string str3 = "";    //从原num值中取出的值
                string str4 = "";    //数字的字符串形式
                string str5 = "";  //人民币大写金额形式
                int i;    //循环变量
                int j;    //num的值乘以100的字符串长度
                string ch1 = "";    //数字的汉语读法
                string ch2 = "";    //数字位的汉字读法
                int nzero = 0;  //用来计算连续的零值是几个
                int temp;            //从原num值中取出的值
     
                num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数
                str4 = (num * 100).ToString();        //将num乘100并转换成字符串形式
                j = str4.Length;      //找出最高位
                if (j > 15) { return "溢出"; }
                str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如:200.55,j为5所以str2=佰拾元角分
     
                //循环取出每一位需要转换的值
                for (i = 0; i < j; i++)
                {
                    str3 = str4.Substring(i, 1);          //取出需转换的某一位的值
                    temp = Convert.ToInt32(str3);      //转换为数字
                    if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                    {
                        //当所取位数不为元、万、亿、万亿上的数字时 
                        if (str3 == "0")
                        {
                            ch1 = "";
                            ch2 = "";
                            nzero = nzero + 1;
                            if (i == (j - 2))//如果有"0角"则不显示零
                            {
                                nzero = 0;
                            }
     
                        }
                        else
                        {
                            if (str3 != "0" && nzero != 0) //如果是连续的0时
                            {
     
                                ch1 = "" + str1.Substring(temp * 1, 1);
                                ch2 = str2.Substring(i, 1);
                                nzero = 0;
                                 
                            }
                            else
                            {
                                ch1 = str1.Substring(temp * 1, 1);
                                ch2 = str2.Substring(i, 1);
                                nzero = 0;
                            }
                        }
                    }
                    else
                    {
                        //该位是万亿,亿,万,元位等关键位
                        if (str3 != "0" && nzero != 0)//前面有零的除0之外的数
                        {
                            ch1 = "" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else //前面没零或 str3=0
                        {
                            if (str3 != "0" && nzero == 0) //值不是0时 前面没零只转换字符
                            {
                                ch1 = str1.Substring(temp * 1, 1);
                                ch2 = str2.Substring(i, 1);
                                nzero = 0;
                            }
                            else
                            {
                                if (str3 == "0" && nzero >= 3)
                                {
                                    ch1 = "";
                                    ch2 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    if (j >= 11)
                                    {
                                        ch1 = "";
                                        nzero = nzero + 1;
                                    }
                                    else
                                    {
                                        ch1 = "";
                                        ch2 = str2.Substring(i, 1);
                                        nzero = nzero + 1;
                                    }
                                }
                            }
                        }
                    }
                    if (i == (j - 11) || i == (j - 3) || i == (j - 7))
                    {
                        //如果该位是亿位万元或元位,则必须写上
                        ch2 = str2.Substring(i, 1);
                    }
                    str5 = str5 + ch1 + ch2;
     
                    if (i == j - 1 && str3 == "0")
                    {
                        //最后一位(分)为0时,加上“整”
                        str5 = str5 + '';
                    }
                }
                if (num == 0)
                {
                    str5 = "零元整";
                }
                return str5;
            }
     
            /**/
            /// <summary>
            /// 一个重载,将字符串先转换成数字在调用CmycurD(decimal num)
            /// </summary>
            /// <param name="num">用户输入的金额,字符串形式未转成decimal</param>
            /// <returns></returns>
            public static string CmycurD(string numstr)
            {
                try
                {
                    double num = Convert.ToDouble(numstr);
                    return CmycurD(num);
                }
                catch
                {
                    return "非数字形式!";
                }
            }
    View Code

     以管理员身份运行某程序

    有一条case需要测试non-admin用户下运行软件产生的event信息。 由于Automation的大job是在admin用户下运行的,因此需要切换到non-admin用户,而这无论是在WTT中还是.NET中切换用户都是比较困难的。因此需要采用run as的策略,也就是在当前的admin用户下,通过code来使得所测软件在non-admin用户下运行。

    下面这段代码实现了在指定的用户下运行某程序。可以从config文件中读取指定的用户。
    注意:指定用户的密码不能为空,否则会有异常抛出。

    public static bool LauchMontanaBrt(string inUserName,string inPassWord)
            {
                try
                {
                    Process MBRTProcess = new Process();
                    MBRTProcess.StartInfo.UserName = inUserName;
                    string strPWD = inPassWord;
                    SecureString password = new SecureString();
                    foreach (char c in strPWD.ToCharArray())
                    {
                        password.AppendChar(c);
                    }
                    MBRTProcess.StartInfo.Password = password;
                    MBRTProcess.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    MBRTProcess.StartInfo.FileName = "xxx.exe";
                    MBRTProcess.StartInfo.Arguments = "/run /wu";
                    MBRTProcess.StartInfo.UseShellExecute = false;
                    MBRTProcess.Start();
                    return true;
                }
                catch(Exception error)
                {
                    Console.writeline(error.Message);
                    return false;
                }
            }
    View Code
  • 相关阅读:
    python_day16_闭包_装饰器
    高阶函数_递归函数_内置函数
    python_day14_函数_返回值_局部和全局变量
    python_day14_set_回到了python的学习
    grep_sed_awl_vim
    jQuery学习之选择器
    css3之其他的属性
    css3之响应式
    css3之各种布局
    css3之各种变形
  • 原文地址:https://www.cnblogs.com/praybb/p/5454487.html
Copyright © 2011-2022 走看看