Thursday, July 12, 2012

Open cmd.exe in specific directory

If you need to open cmd.exe in specific directory and run a command, here is what you need to do:

var processStartInfo = new ProcessStartInfo();
processStartInfo.WorkingDirectory = @"c:\";
processStartInfo.FileName = "cmd.exe";

// set additional properties     
Process proc = Process.Start(processStartInfo);

Wednesday, July 11, 2012

Representing quotes inside string in C#


For:
Ana said "apples"!

string myString = "Ana said \"apples\"!";
string myString = @"Ana said ""apples""!";

Rules:
 - add \ before quotes you want to keep;
 - double the quotes and use @ at the begining.

Working with XML

1. Format xml file so it looks nice:


 public static String FormatXML(String XML)
        {
            String Result = "";


            MemoryStream mStream = new MemoryStream();
            XmlTextWriter writer = new System.Xml.XmlTextWriter(mStream, Encoding.Unicode);
            XmlDocument document = new XmlDocument();


            try
            {
                // Load the XmlDocument with the XML.
                document.LoadXml(XML);


                writer.Formatting = Formatting.Indented;


                // Write the XML into a formatting XmlTextWriter
                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();


                // Have to rewind the MemoryStream in order to read
                // its contents.
                mStream.Position = 0;


                // Read MemoryStream contents into a StreamReader.
                StreamReader sReader = new StreamReader(mStream);


                // Extract the text from the StreamReader.
                String FormattedXML = sReader.ReadToEnd();


                Result = FormattedXML;
            }
            catch (XmlException)
            {
            }


            mStream.Close();
            writer.Close();


            return Result;
        }


2. To be continued...