C#簡單入門

來源:互聯網
上載者:User

標籤:tor   doc   text   pen   一個   .com   reflect   exec   ase   

公司給的一個小的practice

C# vs2017

Stage 1 (cmd)
1. Parse the dll (reflection)
2. Write all the public methods to a txt file (io)

Stage 2 (cmd)
1. Create a local database table
2. Read the txt file about the methods
3. Store the methods to datatable (ado.net)

Stage 3 (cmd)
1. Read the methods from database
2. generate two files to store the methods (one by json format, one by xml format)
3. Use (linq) to read the json file, count the public methods those under a dll, store it to a txt file

 

Stage1 解析一個dll並取出裡面所有的public方法,寫入到txt中。先解析,用反射即可,這裡要注意,因為有的dll是有其他依賴所以可能會無法解析,這裡可以選擇自己寫一個dll,然後嘗試解析它。解析之後將其中的public方法寫入txt中。

using System;using System.Reflection;using System.IO;namespace Stage1{    class Program    {        //解析dll,將public方法寫入txt        static void Main(string[] args)        {            StreamWriter sw = new StreamWriter(@"D:\\C#source\result.txt"); ;            //擷取assembly            Assembly asb = Assembly.LoadFrom(@"D:\C#source\Stage1\Temp\bin\Debug\netcoreapp2.0\Temp.dll");            //擷取module            Module[] modules = asb.GetModules();            foreach (Module module in modules)            {                //擷取type                Type[] types = module.GetTypes();                foreach (Type type in types)                {                    //擷取method                                        MethodInfo[] mis = type.GetMethods();                    foreach (MethodInfo mi in mis)                    {                        sw.Write("Type:" + mi.ReturnType + "     Name:" + mi.Name+ "\r\n");                    }                }            }            sw.Close();            Console.ReadKey();        }    }}

 

Stage2 建立一個資料庫表,將txt中的方法讀入資料庫表中。這裡要注意的就是,添加依賴的時候直接從NuGet中選擇就好,因為以前寫java比較多,這個就類似於java裡的maven工具,自動添加依賴而不用手動添加。

using MySql.Data.MySqlClient;using System;using System.IO;using System.Text;namespace Stage2{    class Program    {        //txt中方法寫入資料庫        static void Main(string[] args)        {            MySqlConnection myconn = new MySqlConnection("Host =localhost;Database=dllmethod;Username=root;Password=314159");            myconn.Open();            MySqlCommand mycom = null;                       int index = 1;                       //讀取txt            StreamReader sr = new StreamReader(@"D:\\C#source\result.txt", Encoding.Default);            String line;            while ((line = sr.ReadLine()) != null)            {                string sql = string.Format("insert into publicmethod(id,type,name) values( ");                //處理line                 string method = line.ToString();                string methodType = method.Substring(5, method.IndexOf("Name") - 5);                string methodName = method.Substring(method.IndexOf("Name:") + 5, method.Length - method.IndexOf("Name:") - 5);                Console.WriteLine(methodType);                Console.WriteLine(methodName);                sql = sql + index + ",\"" + methodType + "\",\"" + methodName + "\")";                mycom= new MySqlCommand(sql, myconn);                mycom.ExecuteNonQuery();                index++;            }            Console.ReadKey();                        myconn.Close();        }    }}

 

Stage3 把public方法從資料庫中都出來,一個導成json格式,一個導成xml格式,資料與json資料的轉換隻需要序列化與還原序列化即可,同時需要依賴一個Json Newtonsoft包,xml格式只需要一個XML包即可。linq讀取json儲存的txt中,將json中的資料還原序列化取出即可。

using MySql.Data.MySqlClient;using Newtonsoft.Json;using System;using System.Collections.Generic;using System.IO;using System.Text;using System.Xml.Linq;namespace Stage3{    class Program    {        static void Main(string[] args)        {            ToJson();            ToXML();            LinqToTxt();            Console.ReadKey();        }        //linq讀取json,儲存到txt中        static void LinqToTxt()        {            //從json中讀出            string fp = "D:\\C#source/MyJSON.json";            string json=File.ReadAllText(fp);            Console.WriteLine(JsonConvert.DeserializeObject(json));            //寫入txt中            StreamWriter sw = new StreamWriter("D:\\C#source/JsonToTxt.txt");            string w = JsonConvert.DeserializeObject(json).ToString();            sw.Write(w);            sw.Close();        }        //產生json        static void ToJson()        {            List<method> methods = getMethodFromDB();                        string fp = "D:\\C#source/MyJSON.json";            if (!File.Exists(fp))  // 判斷是否已有相同檔案             {                FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);                fs1.Close();            }            File.WriteAllText(fp, JsonConvert.SerializeObject(methods));                        Console.WriteLine();        }        //產生xml        static void ToXML()        {            List<method> methods=getMethodFromDB();            XDocument document = new XDocument();            XElement root = new XElement("Public");            XElement book = null;            foreach (method method in methods)            {                book = new XElement("Method"+method.id);                book.SetElementValue("type", method.type);                book.SetElementValue("name", method.name);                root.Add(book);            }                        root.Save("d:\\C#source/MyXML.xml");            Console.WriteLine();        }        //擷取資料庫中內容        static List<method> getMethodFromDB()        {            List<method> methods = new List<method>();            MySqlConnection myconn = new MySqlConnection("Host =localhost;Database=dllmethod;Username=root;Password=314159");            myconn.Open();            MySqlCommand sqlCmd = new MySqlCommand();            sqlCmd.Connection = myconn;            sqlCmd.CommandText = "select * from publicmethod";            MySqlDataReader rec = sqlCmd.ExecuteReader();            //讀取publicmethod表中的內容到methods中            while (rec.Read())            {                Console.WriteLine(" " + rec.GetInt32(0) + " " + rec.GetString(1) + " " + rec.GetString(2));                methods.Add(new method                {                    id = "" + rec.GetInt32(0),                    type = "" + rec.GetString(1),                    name = "" + rec.GetString(2)                });            }            myconn.Close();            return methods;        }    }    class method    {        public string id { get; set; }        public string type { get; set; }        public string name { get; set; }            }}

 

C#簡單入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.