About. NET process usage and various uses summary (ii): Start cmd.exe with process to finish compiling CS into DLL

Source: Internet
Author: User

Previous Chapter Blog I have introduced all the basic use of the process class, this chapter blog I have to do a small extension, to familiarize yourself with the actual use of the process class, not much to say we start to demonstrate.

Let's take a look at the layout of our software design.

  

First we need to give the DLL that we will use, remember the reference in VS? We do not need to import all of the references in this, but we need to import all of the DLLs we used, otherwise we will not be prompted to find the class method.

  

Some students may not know how to view a class or a method of the DLL, in fact, only with the method or class by pressing F12 can see the DLL in the open document, including the path of the DLL is written very clear.

  

My next update is to complete the import project, read out the project CS files and resources, select the CS files and resources that need to be compiled, and then click Compile, complete the compilation, but the function is more, I will slowly update, not updated a version will be attached to the blog below the address.

  

Introduction to the end, we began to explain the implementation of the code, because the entire code of the project and we need to explain the content of irrelevant, so I only pick out the core features here, other content please download the project to see. First put the code, I feel the code in the comments have been written very clear, but I still find some explanations of the comments are not very clear where the detailed explanation.

  

 // <summary>        ///executing the compilation asynchronously/// </summary>        Private Async voidCompiled () {//Note: The following variables are available in advance because the UI is not accessible across threads, and asynchronous operations are also considered multithreaded. //the output path of the DLL            stringWorking =Path_textbox.text; //the name of the DLL            stringName =Name_textbox.text; //vs Path, here we use a batch file of VS to compile the DLL, it will automatically help us to configure the environment, although we directly use. NET csc.exe can also compile, but you see my code used in the c#6.0 of the various new syntax is required compiler support, Using only. NET Csc.exe is unable to complete the compilation            stringVs_path = Vs_path_textbox.text +"\\Common7\\Tools\\VsMSBuildCmd.bat"; //This is not a new syntax, this and the above async is a pair, you give a method tag on async means that this method is asynchronous, but note that await the code outside the wait for synchronous execution, that is, the main thread execution, The code that needs to be executed must be placed in Task.run () before it is executed asynchronously, and I have this misconception in the first place that I have been wondering why Async still cards.             awaitTask.run (() =            {                //Create a ProcessStartInfo, set the initial informationSystem.Diagnostics.ProcessStartInfo start =NewSystem.Diagnostics.ProcessStartInfo ("Cmd.exe"); //let the application accept input, here we use to input commands to the consoleStart. Redirectstandardinput =true; //let the application output data, here we are going to read the output data of the console after compiling to determine whether the compilation was successful, but temporarily unable to complete this functionStart. Redirectstandardoutput =true; //This property is set to True to let the console open without windows to achieve the effect we wantStart. CreateNoWindow =true; //This property does not know what to do, but you want to control the console, this property must be set to false, otherwise it will throw an exception to tell you that you must set this property to FalseStart. UseShellExecute =false; //finally began to get to the point, as the previous chapter of the blog introduced, we initialize a process object through ProcessStartInfoSystem.Diagnostics.Process Process =System.Diagnostics.Process.Start (Start); //here is the process like the console input command, to read the data from the console, call Standardoutput.readline () directly, you can read a line, but notice that you call this method, the console will always wait for an input, So it's easy to get stuck in there. Do not execute the following code//The Getletter method is that I myself define a fetch path in the drive letter plus: With this method to get to the disk of VS, and then directly to the command to CMD, you can enter the disk partition of VS, do not understand to fill the console commandprocess.                Standardinput.writeline (Getletter (Vs_path)); //enter the path to the Vsmsbuildcmd.bat batch file with the CD commandProcess. Standardinput.writeline ("adb"+System.IO.Path.GetDirectoryName (Vs_path)); //get the name of the Vsmsbuildcmd.bat file and enter the command to CMD to execute the batch fileprocess.                                Standardinput.writeline (System.IO.Path.GetFileName (Vs_path)); //after the batch file has been executed, our console environment is set up and we turn the path back to the DLL's output directoryprocess.                Standardinput.writeline (Getletter (working)); Process. Standardinput.writeline ("CD"+working); //The DLLs that will be used are stitched together with "," for the delimiters. Here I explain what the DLL will be used for, assuming that our class calls third-party DLLs and the like, of course, you call the System.Windows.MessageBox (), and so on, you need to refer to the corresponding DLL.
Do not know the method used or the class is in which DLL? On your method or class, press F12 at the top of the document you are writing. //StringBuilder is an efficient string concatenation class, but the corresponding function is not more than string, after stitching all the strings, the direct ToString will be able to get the stringStringBuilder DLL =NewStringBuilder (); foreach(stringIteminchDllPath) {DLL.} Append (item); Dll. Append (","); } //will need to compile the CS file with a space for the delimiter concatenation together, here with spaces, DLLs used, this is the syntax, don't ask me why. StringBuilder cs =NewStringBuilder (); foreach(stringIteminchCspath) {cs. Append (item); Cs. Append (" "); } //if no other DLLs are used if(DLL.) ToString () = ="") { //because the DLL is not being used. //I'm one by one to explain what these commands are for. CSC is the application used to compile our CS file,/t:library on behalf of us to compile the CS file into a DLL, of course, can be compiled into EXE and the like, and then with the above grid plus all the CS files that need to be compiled. Then use/out: Specify the name of the outputProcess. Standardinput.writeline ($"Csc/t:library {cs. ToString ()}/out:{name}"); } Else { //Other DLLs are used in cases where the others are the same as above. The main formula adds/R:,/R: Follow up with all DLLs, with "," splitProcess. Standardinput.writeline ($"Csc/r:{dll. ToString ()}/t:library {cs. ToString ()}/out:{name}"); } //All commands are executed, so let's leave the console with an exit command for the rest of the time .Process. Standardinput.writeline ("Exit"); //wait for the console to closeprocess. WaitForExit (); //release all resources for the process objectprocess. Close (); //Execute the event, here is a new syntax,?. Indicates that the compiledendevent is not NULL for the departure compiledendevent eventCompiledendevent?. Invoke (); }); }

  

string " \\Common7\\Tools\\VsMSBuildCmd.bat ";

Let's explain vsmsbuildcmd.bat this batch file, vs2013 and vs2015 I have confirmed that Vsmsbuildcmd.bat is located under the path of the VS installation path under a specified path, so I have been here for a long time to splice the string. If the lower version vs path differs, you can look at the changes. The Vsmsbuildcmd.bat file did some compiling for us, and instead of executing the file, we could not compile some of the new syntax for C # by directly executing the csc.exe in the. NET directory. One thing to understand is that the C # version and the. NET version have little or nothing to do with it, and the new version of C # syntax is actually maintained by the compiler, so we just can't recognize the new syntax with csc.exe.

  

Briefly introducing some async and await, this is the c#5.0 added two keywords, he let us write asynchronous method becomes exception method, through the above code you can also see that this method can be mixed asynchronous and synchronous operation, we can use await in the method waiting for a time-consuming operation, The following method will not continue until this operation is completed, and the thread is not blocked. Only the Task.run () method is executed asynchronously, which greatly facilitates many of our operations. I have already told you how to use each other to look at the use of it. Yes, don't use unity, unity is c#4.0 syntax and. Net2.0 version, unable to support these two keywords.

The rest is nothing to say, the notes have been written very clearly. Let me tell you about the new syntax for the c#6.0 used in this code.

The first is the "$" operator, which is to simplify string. Format (); The method is designed, I give a $ operator and a string. In contrast to the example of format, you will be simple and clear.

stringA ="I'm", B ="is a", C ="who", d ="? ";strings = $"{ A} in the end {B}{c} yes {d}";stringS2 =string. Format ("{ 0] {1}{2} yes {3}", A, B, C, D);

Looking at the example above, the two ways of stitching strings, using the $ operator, can reduce our workload and increase reading. Their output is naturally the same.

Then the formula? Operator, Chinese name is forgotten, but do not care about such a thing. This operator is still a simplification of our work, see the code below, so it's easy to understand.

NULL ; // the wording we used to do if NULL )    KK. S (); // and use? operator, which means that KK is executed if KK is not null. S (); With the above two lines of code a function KK? S ();

Said?. operator, you have to mention it? Operator?. operator represents non-null when executing,?? operator is represented as NULL when executed. See section Code:

NULL ; // the wording we used to do if NULL )    new  LL (); // and use? Operator new LL ();

Well, thank you for reading this blog, I hope you can have something to gain. The process class and the ProcessStartInfo class also have many functions, we can go to more research research, have the opportunity, I will continue to share in the subsequent chapters for you.

Attached to the entire project source code, the project is vs2015 written in the WPF program, using a large number of c#6.0 new syntax, a low version of the Open will prompt a large number of errors, vs2013 seems to be able to compile normally, have not tried, and then the lower version can not be used. However, only a few incompatible minor errors in the project can be modified to compile properly.

If you just want to run the program, find the DLL compiler. EXE directly in the Bin\release directory in the project directory and copy it away.

There are a lot of problems with the project, such as the inability to get the results of the compilation, not the most recent operation information log, these issues I will follow up and update on this page, each revision I will write the version.

1.0 Beta version: Http://files.cnblogs.com/files/menghuijinxi/DLL%E7%BC%96%E8%AF%91%E5%99%A8.zip

Article original, welcome reprint, please indicate the source.

About. NET process usage and various uses summary (ii): Start cmd.exe with process to finish compiling CS into DLL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.