C# – 자주 쓰는 코드들 (정리중)

#1 실행경로

string aaa = Application.StartupPath + "\\version_history.txt";

#2 파일 읽기

using (StreamReader sr = new StreamReader(file경로, System.Text.Encoding.Default))
{
    aaa = sr.ReadToEnd();
    sr.Close();
}

#3 파일 쓰기

string strDir = "저장할경로";
string strPath = strDir + "\\" + 파일명;

// 저장할 내용
string inputText = rtxtOrgMsg.Text;

// 디렉토리가 존재하지 않으면 디렉토리 생성
if(!Directory.Exists(strDir))
{
    Directory.CreateDirectory(strDir);
}

// text내용을 바이트로 인코딩   
Byte[] info = new UTF8Encoding(true).GetBytes(inputText);

// 저장
FileStream fs = File.Open(strPath, FileMode.Create);
fs.Write(info, 0, info.Length);
fs.Close();

#4 크로스 쓰레드 오류 방지

CheckForIllegalCrossThreadCalls = false;

#5 커서 바꾸기

using (Cursor.Current = Cursors.WaitCursor)
{
    실행코드;
}

#6 사용자 확인후 진행

void btnRemoveEntryClick(object sender, System.EventArgs e)
{
    // 사용자 확인
    if (MessageBox.Show("This entry will be removed.", "Confirm Removal", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) != DialogResult.OK)
        return;

    // OK 일때의 작업은 여기에
    ~~~~
}

#7 진행 시간 측정

DateTime startTime = DateTime.Now;
// 작업작업
MessageBox.Show("Passed!\n\n" + (DateTime.Now - startTime).TotalMilliseconds + " ms.", "Test Result", MessageBoxButtons.OK, MessageBoxIcon.Information);

#8 실행 경로 구하기

System.Environment.CurrentDirectory
Application.StartupPath

#9 richTextBox 자동 스크롤

private void InsertTextProcess(string argText)
{
    this.richTextBoxDescription.Focus();
    this.richTextBoxDescription.AppendText(argText);
    this.richTextBoxDescription.ScrollToCaret();
}

 

4개의 댓글

    • 개인적으로 정리하는 공간이여서 구독자가 있는지도 몰랐습니다.
      몇달동안 방치했는데, 앞으로 자주 포스팅해야겠네요.. ^^

댓글 남기기