C#开发总结【空】

1.调用其他程序

 Process p = new Process();
            p.StartInfo.WorkingDirectory = Application.StartupPath;
            per = 50;
            p.StartInfo.FileName = frmNewAll.AW_TOOL_PATH + "\\df\\make_ext4fs.exe";
            p.StartInfo.Arguments = " -s -l 512M  -a system systemnew.img  system\\";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            try
            {
                p.Start();
                p.OutputDataReceived += new DataReceivedEventHandler(p_Outrom);
                p.BeginOutputReadLine();
            }
            catch (Exception err)
            {
                MessageBox.Show("Error: " + err.Message);
            }
            while (!p.HasExited)
            {
                p.WaitForExit();

            }



2.操作ini配置文件

        private static void updateBootfsIni()
        {
            INIClass iniHelper = new INIClass(frmNewAll.AW_TOOL_PATH + "\\df\\bootfs.ini");
            iniHelper.IniWriteValue("c","fsname",frmNewAll.AW_TOOL_PATH+"\\df\\bootloader.lhs");
            iniHelper.IniWriteValue("c", "root0", frmNewAll.AW_TOOL_PATH + "\\bl");
        }


3.非主线程中,操作UI

在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误的做法,Invoke 和 BeginInvoke 就是为了解决这个问题而出现的,使你在多线程中安全的更新界面显示。

正确的做法是将工作线程中涉及更新界面的代码封装为一个方法,通过 Invoke 或者 BeginInvoke 去调用,两者的区别就是一个导致工作线程等待,而另外一个则不会。

NewMainUI.Invoke(new Action<int>(NewMainUI.changeProgBar), 40);


4.打log,文件IO
Console.WriteLine("copy OK  ");
File.Move(frmNewAll.REPACK_IMG, destRom);

5.通过输出流生成文件
        private static void saveBuildProp(string buildPropStr)
        {
            FileStream fs = new FileStream(frmMain.BUILD_PROP_PATH, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(buildPropStr);
            sw.Close();
            fs.Close();

        }



6.拷贝文件夹

private static string CopyFolder(string sPath, string dPath)
        {
            string flag = "success";
            try
            {
                // 创建目的文件夹
                if (!Directory.Exists(dPath))
                {
                    Directory.CreateDirectory(dPath);
                }

                // 拷贝文件
                DirectoryInfo sDir = new DirectoryInfo(sPath);
                FileInfo[] fileArray = sDir.GetFiles();
                foreach (FileInfo file in fileArray)
                {
                    file.CopyTo(dPath + "\\" + file.Name, true);
                }

                // 循环子文件夹
                DirectoryInfo dDir = new DirectoryInfo(dPath);
                DirectoryInfo[] subDirArray = sDir.GetDirectories();
                foreach (DirectoryInfo subDir in subDirArray)
                {
                    CopyFolder(subDir.FullName, dPath + "//" + subDir.Name);
                }
            }
            catch (Exception ex)
            {
                flag = ex.ToString();
            }
            return flag;
        }
       


7.增强for循环,集合类,与java相同


        private static ArrayList forEach(string inputpath)
        {
            DirectoryInfo dir = new DirectoryInfo(inputpath);
            ArrayList tmp = new ArrayList();
          foreach(DirectoryInfo dChild in dir.GetDirectories("*"))
            {
                tmp.Add(dChild.FullName);
                ArrayList arr = forEach(dChild.FullName);
                foreach(string s in arr)
                {
                    tmp.Add(s);
                }
            }
            foreach (FileInfo fChild in dir.GetFiles("*"))
            {
                tmp.Add(fChild.FullName);
            }
            return tmp;
        }



8.正则表达式搜索字符串

        public static string getPropertyFromBuildProp(string filePath , string key)
        {
            string value = "";
            using (StreamReader sr = new StreamReader(filePath))
            {
                string s;
                string pattern = @key.Trim();
                while ((s = sr.ReadLine()) != null)
                {
                    //Console.WriteLine(tag + "getPropertyFromFile  s   " + s);
                    if (System.Text.RegularExpressions.Regex.IsMatch(s, pattern))
                    {
                        value = s;
                    }
                }
            }
            //Console.WriteLine(tag + "getPropertyFromFile  " + key + "   " + value);
            return value.TrimStart((key+"=").ToCharArray());
        }



9.数据字典


       internal static Dictionary<string, string> initBuildPropHT(string build_prop)
        {
            Dictionary<string, string> properties = new Dictionary<string, string>(64);
            using (StreamReader sr = new StreamReader(build_prop))
            {
                string s;
                int i = 0;
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("="))
                    {
                        string[] kv = s.Split("=".ToCharArray());
                        string k = kv[0];
                        string v = kv[1];
                        properties.Add(k, v);
                        //Console.WriteLine("  initBuildPropHT  " + k + "   " + v);
                    }
                    else
                    {
                        properties.Add("LETOU" + (++i), s);
                    }
                }
            }

            return properties;
        }


        internal static string getStringFromBuildPropDict(Dictionary<string, string> buildPropHT)
        {
            IDictionaryEnumerator enumerator = buildPropHT.GetEnumerator();
            StringBuilder sb = new StringBuilder(1024);
            while (enumerator.MoveNext())
            {

                if (!enumerator.Key.ToString().StartsWith("LETOU"))
                {
                    sb.Append(enumerator.Key.ToString() + "=");
                }
                sb.Append(enumerator.Value.ToString() + "\n");
            }
            return sb.ToString();
        }




10.获取提示框确认
        internal static bool getConfirm(string msg)
        {
            
            return (MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
        }



11.搜寻修改字符串


      internal static void updateItemSingleValue(string k, string v, string ITEM_PATH)
        {
            StringBuilder sb = new StringBuilder(2048);
            using (StreamReader sr = new StreamReader(ITEM_PATH))
            {
                string s;
                string pattern = @k.Trim();
                while ((s = sr.ReadLine()) != null)
                {
                    
                    if (System.Text.RegularExpressions.Regex.IsMatch(s, pattern))
                    {
                        sb.Append(k + "\t\t" + v);
                        Console.WriteLine(tag + "updateItemSingleValue  :" + k + "\t\t" + v);
                    }
                    else
                    {
                        sb.Append(s);
                    }
                    sb.Append(Environment.NewLine);
                }
                
            }

            
            FileStream fs = new FileStream(ITEM_PATH, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(sb.ToString());
            sw.Close();
            fs.Close();

        }



12.获取环境变量

     static string getAdbPath() 
        { 
            // 把环境变量中所有的值取出来,放到变量environment中 
            IDictionary environment = Environment.GetEnvironmentVariables(); 

            // 打印表头 
            //Console.WriteLine( "环境变量名\t=\t环境变量值 "); 

            // 遍历environment中所有键值 
            foreach (string environmentKey in environment.Keys) 
            { 
                // 打印出所有环境变量的名称和值 
                //Console.WriteLine( "{0}\t=\t{1} ", environmentKey, environment[environmentKey].ToString());
                if (environment[environmentKey].ToString().Contains("platform-tools"))
                {
                    int eq = environment[environmentKey].ToString().IndexOf("=");
                    int len = environment[environmentKey].ToString().Length;
                    string tempEnv = environment[environmentKey].ToString().Substring(eq+1, len);
                    if (tempEnv.Length > 0) 
                    {
                        string[] paths = tempEnv.Split(';');
                        foreach ( string path in paths)
                        {
                            if (path.Contains("platform-tools") && File.Exists(path+"\\adb.exe"))
                            {
                                Console.WriteLine(path);
                                return path + "\\adb.exe";
                            }
                        }
                    }
                    //Console.WriteLine("{0}\t=\t{1} ", environmentKey, environment[environmentKey].ToString());
                }
            } 
            //Console.Read(); 
            return "";
        }




13.计算文件MD5值


        /// <summary>
        /// 计算文件的 MD5 值
        /// </summary>
        /// <param name="fileName">要计算 MD5 值的文件名和路径</param>
        /// <returns>MD5 值16进制字符串</returns>
        public static string MD5File(string fileName)
        {
            return HashFile(fileName, "md5");
        }

        /// <summary>
        /// 计算文件的哈希值
        /// </summary>
        /// <param name="fileName">要计算哈希值的文件名和路径</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值16进制字符串</returns>
        public static string HashFile(string fileName, string algName)
        {
            if (!System.IO.File.Exists(fileName))
                return string.Empty;

            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            byte[] hashBytes = HashData(fs, algName);
            fs.Close();
            return ByteArrayToHexString(hashBytes);
        }

        /// <summary>
        /// 计算哈希值
        /// </summary>
        /// <param name="stream">要计算哈希值的 Stream</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值字节数组</returns>
        public static byte[] HashData(Stream stream, string algName)
        {
            HashAlgorithm algorithm;
            if (algName == null)
            {
                throw new ArgumentNullException("algName 不能为 null");
            }
            if (string.Compare(algName, "sha1", true) == 0)
            {
                algorithm = SHA1.Create();
            }
            else
            {
                if (string.Compare(algName, "md5", true) != 0)
                {
                    throw new Exception("algName 只能使用 sha1 或 md5");
                }
                algorithm = MD5.Create();
            }
            return algorithm.ComputeHash(stream);
        }

        /// <summary>
        /// 字节数组转换为16进制表示的字符串
        /// </summary>
        public static string ByteArrayToHexString(byte[] buf)
        {
            return BitConverter.ToString(buf).Replace("-", "");
            /*
            int iLen = 0;

            // 通过反射获取 MachineKeySection 中的 ByteArrayToHexString 方法,该方法用于将字节数组转换为16进制表示的字符串。
            Type type = typeof(System.Web.Configuration.MachineKeySection);
            MethodInfo byteArrayToHexString = type.GetMethod("ByteArrayToHexString", BindingFlags.Static | BindingFlags.NonPublic);

            // 字节数组转换为16进制表示的字符串
            return (string)byteArrayToHexString.Invoke(null, new object[] { buf, iLen });
             */
        }

        ////////



14.待续

你可能感兴趣的:(多线程,C#)