reference : http://www.dotnetperls.com/regex-escape

You want to see an example of using the Regex.Escape method in the C# programming language found in the System.Text.RegularExpressions namespace. This is a powerful method that helps convert user-specified strings into escaped strings to match in a regular expression. Here we examine the Regex.Escape method in the .NET Framework, first seeing an example and then discussing possible uses, using the C# language.

Example

The Regex.Escape method is a static method on the Regex type that receives one parameter of string type. The string reference is received and internally the Escape method allocates a new string containing the escaped character sequence and returns its reference. This example shows the use of Regex.Escape on user input.

Program that uses Regex.Escape [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
	// User specified to remove this string.
	string value1 = @"\123";

	// Escape the input.
	value1 = Regex.Escape(value1);

	// Write the escaped input.
	Console.WriteLine(value1);

	// The string we are changing.
	string input1 = @"This is\123a string";

	// Remove the user-specified pattern.
	string output1 = Regex.Replace(input1, value1, "");

	// Write the output.
	Console.WriteLine(output1);
    }
}

Output
    (The backslash character was replaced.)

\\123
This isa string

String variables used. The example shows three strings: the first string value1 is the input that the user specifies. The user in this example specified the exact string "\123". This value is then escaped with Regex.Escape and becomes "\\123". Finally the Regex.Replace method is called and replaces the pattern "\\123".

Regex.Replace call result. Because the escaped string has two backslashes and not just one, the backslash is treated as a character in the regular expression and not an escape code. The Replace method then can match the character group "\123" and remove it from the final result.

Note (please read)

Uses

Here we note some of the uses the Regex.Escape method has in programs targeting the .NET Framework. Because you can always escape strings in the source code that you type in, you will not need to use it in most programs. If your program retrieves input from a user or file that has certain characters in it, you can use Escape to eliminate the chance that those characters will be used incorrectly.

Summary

We looked at an example of using the Regex.Escape method in the C# programming language. This is a powerful static method that can be useful when preparing dynamic input for use in a regular expression method such as Replace or Split. However, we noted that in most programs where the expressions are specified in the source, this method is not required or useful.

Posted by 노을지기

크리스탈 리포트에 연결하기 위해서 dataset을 이용하였다.

하지만 찾지 못해서 그냥 sql 문으로 사용했는데..

마침 내가 찾는 자료가..ㅎㅎ


출처: http://kojaedoo.tistory.com/640


새항목 추가에서 데이터집합을 만듭니다.

image

 

서버탐색기에서 엑세스하고자하는 DataSet1.xsd 에다가 테이블을 끌어옵니다.

image

 

image

 

DataSet1TableAdapters.CustomersTableAdapter adater = new DataSet1TableAdapters.CustomersTableAdapter();

DataSet1.CustomersDataTable dt = adater.GetData();
//foreach (var item in dt)
//{
// Response.Write(item.CompanyName+"<br>");

//}
this.DataList1.DataSource = dt;
this.DataList1.DataBind();

 

DataList에 바인딩해보기

image

 

잘나온다.!

image

 

 

특정 행만 가져오기

 

image

image

image

 

image

이름을 지정하고

image

image

image

 

 

/// <summary>
/// customerID 를 이용해서 하나의 Customers 불러옵니다.
/// </summary>
/// <param name="customerID"></param>
private void GetCustomersData(string customerID)
{
    DataSet1.CustomersDataTable dt = adater.GetDataByCustomers(customerID);
    if (dt.Count > 0)
    {
        Response.Write("ALFKI 회사의 이름은 :" + dt[0].CompanyName);
    }
}

수정

DataSet1.CustomersDataTable dt = adater.GetDataByCustomers(customerID);
if (dt.Count > 0)
{
    dt[0].CompanyName = "kojaedoo Company";
}
this.adater.Update(dt);

 

image

 

추가

DataSet1.CustomersDataTable dt = new DataSet1.CustomersDataTable();
DataSet1.CustomersRow row =  dt.NewCustomersRow();
row.CustomerID = "KJD";
row.CompanyName = "New kojaedoo Company";
row.ContactName = "kojaedoo";
row.ContactTitle = "고객센터";
// .. 등등삽입

dt.AddCustomersRow(row);

this.adater.Update(dt);

image

 

 

삭제

특정행 가져오기에서 처럼 쿼리구성 마법사를 실행합니다. 여기서 Delete 선택

image

 

image

 

image

 

Delete Query가 추가 되었습니다.

image

 

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        //ALFKI

        DataSet1TableAdapters.CustomersTableAdapter adater = new DataSet1TableAdapters.CustomersTableAdapter();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetCustomersData();
                //UpdateCustomers("ALFKI");
                //NewCustomers();
            }
        }

        /// <summary>
        /// Customers 리스트를 불러옵니다.
        /// </summary>
        private void GetCustomersData()
        {

            DataSet1.CustomersDataTable dt = adater.GetData();
            //foreach (var item in dt)
            //{
            //    Response.Write(item.CompanyName+"<br>");

            //}
            this.DataList1.DataSource = dt;
            this.DataList1.DataBind();
        }

        /// <summary>
        /// customerID 를 이용해서 하나의 Customers 불러옵니다.
        /// </summary>
        /// <param name="customerID"></param>
        private void GetCustomersData(string customerID)
        {
            DataSet1.CustomersDataTable dt = adater.GetDataByCustomers(customerID);
            if (dt.Count > 0)
            {
                Response.Write("ALFKI 회사의 이름은 :" + dt[0].CompanyName);
            }
        }

        /// <summary>
        /// Customers를 수정합니다.
        /// </summary>
        /// <param name="customerID"></param>
        private void UpdateCustomers(string customerID)
        {
            DataSet1.CustomersDataTable dt = adater.GetDataByCustomers(customerID);
            if (dt.Count > 0)
            {
                dt[0].CompanyName = "kojaedoo Company";
            }
            this.adater.Update(dt);
        }

        /// <summary>
        /// Customers를 삭제합니다.
        /// </summary>
        /// <param name="customerID"></param>
        private void DeleteCustomers(string customerID)
        {
            int i = this.adater.DeleteQueryCustomerID(customerID);
            Response.Write(i.ToString() + "개가 삭제되었습니다.");
        }

        /// <summary>
        /// 새로운 Customers 를 만듭니다.
        /// </summary>
        private void NewCustomers()
        {
            DataSet1.CustomersDataTable dt = new DataSet1.CustomersDataTable();
            DataSet1.CustomersRow row =  dt.NewCustomersRow();
            row.CustomerID = "KJD";
            row.CompanyName = "New kojaedoo Company";
            row.ContactName = "kojaedoo";
            row.ContactTitle = "고객센터";
            // .. 등등삽입
            
            dt.AddCustomersRow(row);

            this.adater.Update(dt);

        }
    }
}
Posted by 노을지기

@""" 으로 시작하면 된다.
pInfo.Arguments =
@"""C:\Wolf Lair\WorkDeskTemp\" + username + @"\WolfDeskApp2k3.mdb"" /runtime /x _AutoExec";

변수에 대입할 경우
  1. string n=@"C:\Documents and Settings\My Test Folder\TestDoc.doc";
  2. string nn="\""+n+"\"";


Posted by 노을지기

출처: http://zmeun.tistory.com/45

C# 코드로 Dos 명령 실행하기!


 

날씨가 무척이나 덥습니다. 사무실은 다행히 적당히 시원하지만, 잠시 밖에 나간다 하면 ! 하는 소리가 절로 나오네요~. 말복이 지나고 입추가 지났는데도 이렇게 더운 정말 날씨가 미친 걸까요? 개인적으로 가을을 많이 좋아하는데요~ 이럴 때일수록, 좋아라 하는 가을이 한시라도 빨리 왔으면 하는 바램이 굴뚝같습니다.


이번에는
C#코드로 Dos 명령을 실행하는 코드를 살펴보겠습니다. 윈도우에서 실행창(Ctrl+R) 통해 명령을 처리하거나, CMD 창을 이용해 처리하는 명령을 C#코드를 이용해서 사용하는 방법에 대해 간략히 소개해 드리도록 하겠습니다.

 

Process & ProcessStartInfo

.Net Framework 정말 많은 API 제공합니다. 중에서 우리가 이번에 사용하게 객체는 바로 System.Diagnostics 네임스페이스 아래 있는 Process ProcessStartInfo 클래스입니다. Process 클래스는 ProcessStartInfo 클래스에 할당 실행 정보를 이용해 새로운 Process 윈도우에 생성하고 ProcessStartInfo Process 클래스가 실행해야 하는 실행 파일명과 기타 정보들을 담고 있는 클래스입니다.

그럼 클래스를 이용해서, 응용프로그램 파일을 실행하는 코드를 보겠습니다.

ListViewItem lvi1 = new ListViewItem(new string[]{"Paint", "mspaint"});

ListViewItem lvi2 = new ListViewItem(new string[]{"계산기", "calc"});

ListViewItem lvi3 = new ListViewItem(new string[]{"NotePad", "notepad"});

ListViewItem lvi4 = new ListViewItem(new string[]{"MS Office Word", "winword", @"D:\Documents\sample.doc"});

ListViewItem lvi5 = new ListViewItem(new string[]{"MS Office Excel", "excel"});

ListViewItem lvi6 = new ListViewItem(new string[]{"SQL 쿼리분석기", "isqlw"});

ListViewItem lvi7 = new ListViewItem(new string[]{"Internet Explorer", "iexplore", "http://zmeun.tistory.com"});

                               

this.lvPrograms.View = View.Details;

this.lvPrograms.Columns.Add("Program Name", 180, HorizontalAlignment.Center);

                               

this.lvPrograms.Items.Add(lvi1);

this.lvPrograms.Items.Add(lvi2);

this.lvPrograms.Items.Add(lvi3);

this.lvPrograms.Items.Add(lvi4);

this.lvPrograms.Items.Add(lvi5);

this.lvPrograms.Items.Add(lvi6);

this.lvPrograms.Items.Add(lvi7);

[코드 1 실행 응용프로그램 파일 목록]

 

코드는 ListView 컨트롤에 실행시킬 응용프로그램 파일 목록을 담는 코드입니다. 코드에 담겨진 응용프로그램 목록은 윈도우에서 제공하는 그림판과 계산기, 메모장과 Internet Explorer이고, MS Office 있는 MS Word Excel 그리고 MS-SQL Server 있는 쿼리 분석기입니다. (나름 흔히 사용하는 파일들을 예제로 넣어 두었습니다.) 이렇게 추가된 코드는 아래와 같이 나타납니다.

사용자 삽입 이미지
[그림 1 실행 프로그램 목록]

 

저렇게 나타난 목록 중에 맘에 드는 것을 선택 Execute Selected Program 버튼을 클릭하면, CLR 윈도우에 새로운 프로세스를 만들고 안에서 선택한 프로그램을 실행시키게 됩니다. 아래 코드는 목록에 있는 프로그램을 선택 버튼을 클릭하면 실행되는 코드입니다.

string command = this.lvPrograms.SelectedItems[0].SubItems[1].Text;

string args = "";

if(this.lvPrograms.SelectedItems[0].SubItems.Count > 2)

{

   args = this.lvPrograms.SelectedItems[0].SubItems[2].Text;

}

 

System.Diagnostics.Process process = new System.Diagnostics.Process();

process.EnableRaisingEvents = false;

process.StartInfo.FileName = command;

process.StartInfo.Arguments = args;

 

process.Start();

[코드 2 실행 코드]

 

위에서 보셨던, 목록에 실행시킬 프로그램을 추가하는 코드는, 실제 프로그램 명뿐만 안니라, 실행파일명과 실행 시에 할당 Arguments 값까지 가지고 있습니다. Arguments  MS Word Internet Explorer 군데 할당되어 있는데, MS Word 할당 인자는 문서를 지정한 경로값이고, Internet Explorer 할당된 인자는 열어 Page Url입니다.

사용자 삽입 이미지
[그림 2 계산기 실행 결과]


사용자 삽입 이미지

[그림 3 IE 실행 결과]

 

목록에 있는 프로그램 계산기와 Ineternet Explorer 실행 시켜 모습입니다. Internet Explorer에는 http://zmeun.tistory.com 경로를 ProcessStartInfo 클래스의 Arguments 할당하였고, 실행 프로그램 명을 IExplorer 주었습니다. 그래서 IE 실행 Arguments 할당 url 주소를 바로 열리게 되는 것입니다.

 

Execute Dos Command

그럼 이번에는 실제로 Dos 명령을 실행하는 코드를 알아보겠습니다. 역시 이번에도 사용될 클래스는 위에서 말씀드린 Process ProcessStartInfo 개의 클래스 입니다.

System.Diagnostics.Process process = new System.Diagnostics.Process();

System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

startInfo.FileName = "CMD.exe";

startInfo.WorkingDirectory = @"D:\";

 

startInfo.UseShellExecute = false;

startInfo.RedirectStandardInput = true;

startInfo.RedirectStandardOutput = true;

startInfo.RedirectStandardError = true;

 

process.EnableRaisingEvents = false;   

process.StartInfo = startInfo;

process.Start();

process.StandardInput.Write(this.txtCommand.Text + Environment.NewLine);

process.StandardInput.Close();

 

string result = process.StandardOutput.ReadToEnd();

string error = process.StandardError.ReadToEnd();

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("[ Result Info ]\r\n");

sb.Append(result);

sb.Append("\r\n");

sb.Append("[ Error Info ]\r\n");

sb.Append(error);

 

 

this.txtResult.Text = sb.ToString();

 

process.WaitForExit();

process.Close();

[코드 3 Dos 명령 실행 코드]

 

Dos 명령을 실행시키기 위해서 ProcessStartInfo 클래스의 FileName 속성에 실행 파일명을 “CMD.exe” 주고, WorkingDirectory “D:\” 설정합니다. 그리고 중요한 부분인데, ProcessStartInfo 클래스의 RedirectStandardInput RedirectStandardOutput 그리고 RedirectStandError 속성을 모두 true 설정합니다. 속성들은 CMD창에 전달되고, 출력되는 값들을 사용할지 할지를 설정하는 부분입니다. 그리고 개의 속성을 사용하기 위해서는 반드시 UseShellExecute 속성을 false 설정해야 합니다. 그러면 Error 던지게 됩니다.

이제 Dos 명령어를 CMD창에 전달하면 되는데, 이때 사용되는 코드가 Process.StandardInput.Write 코드입니다. Process 전달 값은 Stream으로 처리되며, 코드는 Stream 전달 명령을 쓰게하는 코드입니다. Write 메소드의 인자로 우리가 실행 명령을 할당하면 됩니다. 그리고 중요한 부분이 있는데, 실행 명령 다음에는 항상 캐리지 리턴(“\r\n”) 들어가야 한다는 것입니다. 캐리지 리턴 값이 들어가지 않으면 CMD창은 명령을 인식하지 못하고 맙니다.(사실 이것 때문에 나름 고민했었지요~ 전혀 엉뚱한 메시지를 내보내거든요~ 이런 메시지요 “More ?”… 아주 지대 황당한 시츄레이션이지요~
-_-;; )

전달 명령을 Stream으로 보내면, Process 클래스는 명령을 실행시키고 결과도 Stream으로 내보냅니다. 그게 StandardOutput 속성이고, 이렇게 내보낸 Stream 읽으면 출력 결과를 받을 있습니다. 그리고 친절하게도 명령 실행 발생한 오류도 별도의 Stream 속성으로 제공하는데 바로 StandardError 속성입니다. 속성을 이용하면, 명령 실행 발생한 오류도 받아 있게 됩니다.

사용자 삽입 이미지
[그림 4 Dos 명령 실행 결과]

 

dir명령을 실행하면 StandardOutput 결과를 받아서 출력 값을 그대로 처리 있습니다. 이와 마찬가지로 실행 발생한 오류정보 까지도 StandardError 속성을 이용해 받을 있습니다.

 

이렇게 해서 C#코드를 이용한 Dos 명령 실행에 대해 간략히 알아봤습니다. 내부적으로 어떤 배치를 실행하거나, CMD 명령을 처리할 아마 유용하게 사용 있을 같습니다.

그럼 이만 여기에서 마치겠습니다. 감사합니다. ^O^v
Posted by 노을지기
기본적인 것을 잘 몰라서.. 삽질하는 중..ㅡㅡ;;

fclsChild1 objChild = new fclsChild1();
objChild.MdiParent = this;
objChild.Show();


fclsChild2 objChild = new fclsChild2();
objChild.MdiParent = this.MdiParent;
objChild.Show();

두개를 잘 구분하여 사용하자.ㅡㅡ;;
두번재것의 MidParent를 몰라서.. 완전 삽질했음..ㅡㅡ;;

출처: http://www.informit.com/library/content.aspx?b=STY_Csharp_24hours&seqNum=68
Posted by 노을지기