bloggerads

2013年1月3日 星期四

C# : Call a exe file without a command prompt blinking

using System.Diagnostics;


private static int RunProcess(string processName, string arguments)
{
    Process process = new Process();
    process.StartInfo.FileName = processName;
    process.StartInfo.Arguments = arguments;
 //* 
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;  //Without a command prompt blinking
 //&
    process.Start();
    process.WaitForExit();
    return process.ExitCode;
}

C# : Basic knowledge notes

// int to string

int iValue = 4;
string sResult = iValue.ToString();
string sResult = iValue.ToString("X16");  // int to Hex string

// string to int

string num = "-105";
int numVal = Int32.Parse(num);

// string array

string[] lines= new string[] { "Param1", "Param2" };

Array.Clear(lines, 0, lines.Length); // Clear all (Won't resize)

2013年1月2日 星期三

C# : Write and Read Binary file

using System.IO;
byte[] content = new byte[] {1, 2};
File.WriteAllBytes(@"E:\12.bin", content);
byte[] bytes = File.ReadAllBytes(@"E:\12.bin");
Console.WriteLine("{0:x3}", bytes[0]); // Hex format and 3 digits
Console.WriteLine("{0:D2}", bytes[1]); // Dec format and 2 digits

2013年1月1日 星期二

C# : Write TXT file

Write a struct to a TXT file

struct test{
    public char a;
    public int x;
    public int y;
    public int z;
}

static void Main(string[] args)
{
    test[] aa = new test[] {
        new test { a = 'a', x = 1, y = 2, z = 3 },
        new test { a = 'b', x = 2, y = 3, z = 4 }
    };
    string path = System.IO.Directory.GetCurrentDirectory() + "\\go.txt";
    
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(path))
    {
        foreach (test x in aa)
        {
            file.WriteLine("{0} {1} {1} {3}", x.a.ToString(), x.x, x.y, x.z);
        }
    }

}

C# : Write / Read CSV file sample code

Write an array to test.csv

static void Main(string[] args)
{
    string filePath = System.IO.Directory.GetCurrentDirectory() + @"\test.csv";

    string[] myDataArray = new string[] { "123", "abc", "ddd"};

    File.WriteAllText(filePath, string.Join(",", myDataArray));   
}


Read  test.csv

static void Main(string[] args)
{
    string filePath = System.IO.Directory.GetCurrentDirectory() + @"\test.csv";

    var item = new List<string>();

    foreach (var line in File.ReadLines(filePath))
    {
        var array = line.Split(',');
        foreach (string idx in array)
            item.Add(idx);
    }

    string[] strArray = item.ToArray();

    foreach (string ss in strArray)
    {
        Console.WriteLine("{0}", ss);
    }
    Console.ReadLine();
}