사용자 도구

사이트 도구


사이드바

카테고리

language:csharp:코드-조각
C# 코드 모음 

빈도 높은

MessageBox

MSDN/MessageBox

MessageBox.Show( messageString, CaptionString );

Assert

using System.Diagnostics;
 
Debug.Assert( <조건문> );

가변인자

string s;
s = System.String.Format( "{0} times {1} = {2}", i, j, (i * j) );

String

string to byte 변환

string _dataStr = @"한글과 영문을 섞은 Normal string";
// StringBuilder에 집어 넣은 다음
StringBuilder builder = new StringBuilder( _dataStr );
// 원하는 캐릭터를 변경하고
builder[0] = (char)((int)builder[0] + 4);
// 다시 스트링에 집어 넣는다.
_dataStr = builder.ToString();

스트링 조합

Composite Formatting

조합 스트링의 기본 사용은,

string output = string.Format("{0}{1:D}{2}", "{", value, "}");

나머지 상세 내용은 링크 참조.

String : Format

ToString()에서 소수점 자리수 조정

ToString()만으로 소수점 자리수를 잘라서 표시하기.

float a1 = 0.12345f;
string _msg1 = a1.ToString("n0"); // 0
string _msg2 = a1.ToString("n3"); // 0.123

서식 문자열 기본 사용

string output = string.Format("{0}, {1,3:D}", 1, 2 );

{0} : 첫번째 파라미터를 그대로 반영한다.

{1,3:D} : 두번째 파라미터를 받는다.

  • ',3' 이면 ' ' 공백으로 3자리를 사용한다.
  • ':D' 정수 포맷이라는 지시어.
string output = string.Format("{0:D3}", 21 );
// 결과: 021
  • {0 : 포맷 파라미터 인덱스.
  • : : 파라미터 연장
  • D3 : D는 정수입력이라는 뜻이고, 3은 자리수가 3자리. 빈자리에는 0을 채운다.

포맷 문자열 형식 변환

( "{0}"     , sampleStr )     // 보통은 그냥 알아서 출력 되지만,
( "{0:X}"   , 123 )           // 16진수로 출력
( "{0:C}"   , 123 )           // $123 처럼 돈 표시가 붙어서 출력
( "{0:F}"   , 1234.5678 )     // 1234.5678
( "{0:F2}"  , 34.5678 )       // 1234.56 뒷 두자리만
 
( "{0:D4}"  , 12 )            // 0012
 
( "{0:hh}"  , DateTime.Now )  // 시간 표시
( "{0:mm}"  , DateTime.Now )  // 분 표시

str to int

자주 잊어버리는데.. ( 방법: 문자열을 숫자로 변환(C# 프로그래밍 가이드)

using System; // 네임스페이스를 포함시키려면
 
string str_num = "22";
int nv = System.Convert.ToInt32(str_num);
// or
nv = Int32.Parse(str_num);

char to int

string numberStr = "256";
char[] num_char_ar = numberStr.ToCharArray();
for( int i = 0; i < num_char_ar.Length; ++i )
{
  // 리턴값 형식이 double이라 강제 형변환
	int nv = (int)System.Char.GetNumericValue(num_char_ar[i]);
}

Directory IO

Example

디렉토리 있는지 검사

using System.IO;
// log 폴더가 없으면 만든다.
if(!Directory.Exists("log")) {
  Directory.CreateDirectory("log");
}

특정 폴더의 파일과 서브 폴더 이름을 모두 읽어 오는 간단한 예제

using System.IO; // Directory, File 에 대해서
 
void readDirectory(string targetDir_)
{
  string[] files = Directory.GetFiles(targetDir_);
  foreach(string _filename in files)
    readFiles(_filename);
 
  string[] subdirs = Directory.GetDirectories(targetDir_);
  foreach(string _subdir_path in subdirs)
    readDirectory(_subdir_path);
}
 
void readFiles(string filePath_)
{
  Console.WriteLine("found file: {0}", filePath_);
}

조건을 붙여 필요한 파일이나 폴더 목록을 받아오는 방법 - 우선 링크만

File IO

File Exist

using System;
using System.IO;
 
class Test
{
    public static void Main()
    {
        string sourceFile = @"c:\tests\Test.txt";
        string newFile = @"c:\tests\Test2.txt";
        if (File.Exists(sourceFile)) {
            File.Copy(sourceFile, newFile);
        }
        else {
            Console.WriteLine("Source file does not exist.");
        }
    }
}

Path의 사용

using System.IO;

String samplePath = @"C:\z\z.exe";
// return "Z"
String targetProcName = Path.GetFileNameWithoutExtension( samplePath ).ToUpper();
 
// return "C:\z"
Path.GetDirectoryName( samplePath );

msdn 봐도 되지만 여기서 찾고 끝내는 함수.

GetDirectoryName(String) 경로를 리턴
GetExtension(String) 확장자만 리턴
GetFileName(String) 경로명에서 이름과 확장자를 리턴
GetFileNameWithoutExtension(String) 파일 이름만 리턴

Directory 의 사용

String samplePath = @"C:\z";
if( Directory.Exists( samplePath ) )
  Directory.SetCurrentDirectory( samplePath );

특수한 폴더 경로

  • Environment.GetFolderPath(<param>) : 특수폴더 값을 파라미터로 전달
  • Environment.SpecialFolder.<xxxx> : <xxxx> 에 입력하려는 특수 폴더 상수 값
{
  Console.WriteLine( "GetFolderPath : {0}", 
    Environment.GetFolderPath( Environment.SpecialFolder.System ) );
}

Text IO

File.AppendText Method로 스트링 Append

File.AppendText Method

파일을 만들고, 쓰기까지 좋은 예제

using System;
using System.IO;
 
class Test 
{
  public static void Main() 
  {
    string path = @"c:\temp\MyTest.txt";
    // This text is added only once to the file. 
    if (!File.Exists(path)) 
    {
      // Create a file to write to. 
      using (StreamWriter sw = File.CreateText(path)) 
      {
      	sw.WriteLine("Hello");
      	sw.WriteLine("And");
      	sw.WriteLine("Welcome");
      }	
    }
 
    // This text is always added, making the file longer over time 
    // if it is not deleted. 
    using (StreamWriter sw = File.AppendText(path)) 
    {
    	sw.WriteLine("This");
    	sw.WriteLine("is Extra");
    	sw.WriteLine("Text");
    }	
 
    // Open the file to read from. 
    using (StreamReader sr = File.OpenText(path)) 
    {
    	string s = "";
    	while ((s = sr.ReadLine()) != null) 
    	{
        Console.WriteLine(s);
    	}
    }
  }
}

Binary IO

Control

TextBox 에서 멀티라인

// 총 몇줄인지 확인하기 위해서 쓴 코드
char[] _zsp = new char[] { '\r', '\n' };
String[] logs = mLogView.Text.Split( _zsp );
 
if( logs.Length > maxLogLineCount )
  mLogView.ResetText();
 
// Environment.NewLine를 붙여주면 줄 바꾸기가 된다.
mLogView.AppendText( newLog + Environment.NewLine );

버튼상태조정

SampleButton.Enabled = false; // true면 활성화

System

프로세스 체크

// 예제 프로그램에서 프로세스 이름을 구한다.
// Path를 사용해서 파일이름을 구한다.
String targetProcName = Path.GetFileNameWithoutExtension( mProcPath.Text ).ToUpper();
 
// 1) 전체 프로세스 리스트를 구한다.
Process[] processlist = Process.GetProcesses();
 
// 2) 프로세스 리스트를 순행하면서
foreach(Process tmpproc in processlist)
{
  // 3) 각 프로세스의 이름을 구해서
  String upperProcName = tmpproc.ProcessName.ToUpper();
  // 4) 내가 찾는 프로세스인지 확인
  if( upperProcName == targetProcName )
  {
    // 5) 프로세스의 패스를 구해서 임시 저장 (원래프로그램의 조각코드)
    mProcPath.Text = tmpproc.MainModule.FileName;
    return true;
  }
}
return false;

프로세스실행

public bool StartProcess()
{
  // default value : @"C:\z\z.exe";
  String dcServerFileName = mProcPath.Text;
  String dcServerPath = Path.GetDirectoryName( dcServerFileName );
 
  try
  {
    if( Directory.Exists( dcServerPath ) )
      Directory.SetCurrentDirectory( dcServerPath );
    Process dcProc = Process.Start( dcServerFileName );
    if( null != dcProc )
    {
      return true;
    }
  }
  catch( Win32Exception w )
  {
    // i dont know about this code : I just copied.
    Console.WriteLine( w.Message );
    Console.WriteLine( w.ErrorCode.ToString() );
    Console.WriteLine( w.NativeErrorCode.ToString() );
    Console.WriteLine( w.StackTrace );
    Console.WriteLine( w.Source );
    Exception e = w.GetBaseException();
    Console.WriteLine( e.Message );
  }
  return false;
}

압축

System.IO.CompressionFileStream/MemoryStream을 사용해서 파일 또는 메모리 압축/해제 하는 예제.

파일에 대한 예제는 MSDN에 있으니 그쪽을 보자. DeflateStream

using System.IO.Compression;

압축/압축풀기 코드

public static string Base64Compress( string data )
{
  using( var ms = new MemoryStream() )
  {
    using( var ds = new DeflateStream( ms, CompressionMode.Compress ) )
    {
      byte[] b = Encoding.UTF8.GetBytes( data );
      ds.Write( b, 0, b.Length );
    }
    return Convert.ToBase64String( ms.ToArray() );
  }
} 
 
public static string Decompress( Byte[] bytes )
{
  using( var uncompressed = new MemoryStream() )
  using( var compressed = new MemoryStream( bytes ) )
  using( var ds = new DeflateStream( compressed, CompressionMode.Decompress ) )
  {
    ds.CopyTo( uncompressed );
    return Encoding.UTF8.GetString( uncompressed.ToArray() );
  }
}
 
public static void TEST_FUNC()
{
  string _beforeComp = @"한글이나 영문을 섞어서, test string..";
  string _midBuffer = Base64Compress( _beforeComp );
  string _resultStr = Decompress( Convert.FromBase64String(_midBuffer) );
}

랜덤

// 0~n사이의 랜덤 얻기
Random _rnd = new Random();
int _idx = _rnd.Next( 0, 100 ); // 0 ~ 100 사이의 랜덤 수 얻기

시간 (TimeDate)

로그 출력용 시간 정보 얻기

using system;
DateTime saveNow = DateTime.Now;
string dtString = saveNow.ToString(@"yy/MM/dd hh:mm:ss.ffff");
 
string _finalStr = String.Format("[{0}] {1}", dtString, "무언가 스트링");

Debug

디버그용 메시지 출력

using System.Diagnostics;
 
Debug.WriteLine("디버그 메시지 출력");

그외

실행 중인 프로그램 이름 얻기

using System.Diagnostics;
 
// Returns the filename with extension (e.g. MyApp.exe).
System.AppDomain.CurrentDomain.FriendlyName
 
// Returns the filename without extension (e.g. MyApp).
// (not work)System.Diagnostics.Process.GetCurrentProcess().ProcessName
System.Reflection.Assembly.GetEntryAssembly().Location
 
// Returns the full path and filename (e.g. C:\Examples\Processes\MyApp.exe). 
// You could then pass this into System.IO.Path.GetFileName() or 
// System.IO.Path.GetFileNameWithoutExtension() to achieve the same results as the above.
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

배열

2차 배열을 사용할때, 각 N 차 배열의 개수를 얻고 싶을때

//
int int_array[,] = new int[3,3]; // 3x3 배열을 만든 다음,
 
// 0번째 배열 길이를 얻고 싶으면
int_array.GetLength( 0 ); // 요 함수로 얻는다.
language/csharp/코드-조각.txt · 마지막으로 수정됨: 2022/12/07 22:30 저자 kieuns