사용자 도구

사이트 도구


language:csharp:코드-조각

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
language:csharp:코드-조각 [2016/02/21 18:55]
kieuns [String : Format]
language:csharp:코드-조각 [2022/12/07 22:30] (현재)
kieuns ↷ 문서가 개발_언어:csharp:코드-조각에서 language:csharp:코드-조각(으)로 이동되었습니다
줄 1: 줄 1:
 +{{htmlmetatags>metatag-robots=() 
 +metatag-keywords=(C#,씨썁,C# 코드조각,코드 조각) 
 +metatag-description=(C# 코드조각)
 +}}
  
 +  C# 코드 모음 
 +
 +{{tag>코드조각모음 코드_조각}}
 +
 +====== 빈도 높은 ======
 +
 +===== MessageBox =====
 +[[http://msdn.microsoft.com/ko-kr/library/system.windows.forms.messagebox.aspx|MSDN/MessageBox]]
 +
 +<code csharp>
 +MessageBox.Show( messageString, CaptionString );
 +</code>
 +
 +===== Assert =====
 +
 +<code csharp>
 +using System.Diagnostics;
 +
 +Debug.Assert( <조건문> );
 +</code>
 +===== 가변인자 =====
 +
 +<code csharp>
 +string s;
 +s = System.String.Format( "{0} times {1} = {2}", i, j, (i * j) );
 +</code>
 +
 +
 +===== String =====
 +
 +==== string to byte 변환 ====
 +
 +<code csharp>
 +string _dataStr = @"한글과 영문을 섞은 Normal string";
 +// StringBuilder에 집어 넣은 다음
 +StringBuilder builder = new StringBuilder( _dataStr );
 +// 원하는 캐릭터를 변경하고
 +builder[0] = (char)((int)builder[0] + 4);
 +// 다시 스트링에 집어 넣는다.
 +_dataStr = builder.ToString();
 +</code>
 +
 +==== 스트링 조합 ====
 +
 +[[http://msdn.microsoft.com/en-us/library/txafckwd.aspx|Composite Formatting]]
 +
 +조합 스트링의 기본  사용은,
 +<code csharp>
 +string output = string.Format("{0}{1:D}{2}", "{", value, "}");
 +</code>
 +나머지 상세 내용은 링크 참조.
 +
 +====== String : Format ======
 +
 +  - 합성 형식 지정: http://msdn.microsoft.com/ko-kr/library/txafckwd.aspx
 +  - 표준 숫자 서식 문자열: http://msdn.microsoft.com/ko-kr/library/dwhawy9k.aspx
 +  - 사용자 지정 숫자 서식 문자열: http://msdn.microsoft.com/ko-kr/library/0c899ak8.aspx
 +
 +===== ToString()에서 소수점 자리수 조정 =====
 +
 +ToString()만으로 소수점 자리수를 잘라서 표시하기.
 +
 +<code csharp>
 +float a1 = 0.12345f;
 +string _msg1 = a1.ToString("n0"); // 0
 +string _msg2 = a1.ToString("n3"); // 0.123
 +</code>
 +
 +===== 서식 문자열 기본 사용 =====
 +
 +<code csharp>
 +string output = string.Format("{0}, {1,3:D}", 1, 2 );
 +</code>
 +
 +{0} : 첫번째 파라미터를 그대로 반영한다.
 +
 +{1,3:D} : 두번째 파라미터를 받는다. 
 +  * ',3' 이면 '   ' 공백으로 3자리를 사용한다.
 +  * ':D' 정수 포맷이라는 지시어.
 +
 +<code csharp>
 +string output = string.Format("{0:D3}", 21 );
 +// 결과: 021
 +</code>
 +
 +  * {0  : 포맷 파라미터 인덱스. 
 +  * :   : 파라미터 연장
 +  * D3  : D는 정수입력이라는 뜻이고, 3은 자리수가 3자리. 빈자리에는 0을 채운다.
 +
 +
 +
 +
 +===== 포맷 문자열 형식 변환 =====
 +
 +
 +<code csharp>
 +( "{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 )  // 분 표시
 +</code>
 +
 +
 +===== str to int =====
 +
 +자주 잊어버리는데.. ( [[http://msdn.microsoft.com/ko-kr/library/bb397679.aspx|방법: 문자열을 숫자로 변환(C# 프로그래밍 가이드)]]
 +
 +<code csharp>
 +using System; // 네임스페이스를 포함시키려면
 +
 +string str_num = "22";
 +int nv = System.Convert.ToInt32(str_num);
 +// or
 +nv = Int32.Parse(str_num);
 +</code>
 +
 +===== char to int =====
 +
 +<code csharp>
 +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]);
 +}
 +</code>
 +====== Directory IO ======
 +
 +===== LINK =====
 +
 +  * [[http://msdn.microsoft.com/en-us/library/System.IO.Directory_methods.aspx|Directory Methods]]
 +  * [[http://msdn.microsoft.com/en-us/library/54a0at6s.aspx|Directory.CreateDirectory]]
 +  * [[http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx|Directory.Exists]]
 +
 +===== Example =====
 +
 +====디렉토리 있는지 검사====
 +
 +<code csharp>
 +using System.IO;
 +// log 폴더가 없으면 만든다.
 +if(!Directory.Exists("log")) {
 +  Directory.CreateDirectory("log");
 +}
 +</code>
 +
 +====특정 폴더의 파일과 서브 폴더 이름을 모두 읽어 오는 간단한 예제====
 +
 +<code csharp>
 +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_);
 +}
 +</code>
 +
 +조건을 붙여 필요한 파일이나 폴더 목록을 받아오는 방법 - 우선 링크만
 +
 +  * [[https://docs.microsoft.com/ko-kr/dotnet/standard/io/how-to-enumerate-directories-and-files|방법: 디렉터리 및 파일 열거]]
 +
 +====== File IO ======
 +
 +  * [[http://msdn.microsoft.com/en-us/library/ms404278.aspx|Common IO Task example]]
 +
 +===== File Exist =====
 +<code csharp>
 +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.");
 +        }
 +    }
 +}
 +</code>
 +
 +===== Path의 사용 =====
 +
 +using System.IO;
 +
 + * [[http://msdn.microsoft.com/ko-kr/library/system.io.path(v=vs.110).aspx|System.IO.Path]]
 +
 +<code csharp>
 +String samplePath = @"C:\z\z.exe";
 +// return "Z"
 +String targetProcName = Path.GetFileNameWithoutExtension( samplePath ).ToUpper();
 +
 +// return "C:\z"
 +Path.GetDirectoryName( samplePath );
 +</code>
 +
 +msdn 봐도 되지만 여기서 찾고 끝내는 함수.
 +
 +| GetDirectoryName(String) | 경로를 리턴 |
 +| GetExtension(String) | 확장자만 리턴 |
 +| GetFileName(String) | 경로명에서 이름과 확장자를 리턴 |
 +| GetFileNameWithoutExtension(String) | 파일 이름만 리턴 |
 +
 +===== Directory 의 사용 =====
 +<code csharp>
 +String samplePath = @"C:\z";
 +if( Directory.Exists( samplePath ) )
 +  Directory.SetCurrentDirectory( samplePath );
 +</code>
 +
 +===== 특수한 폴더 경로 =====
 +
 +  * Environment.GetFolderPath(<param>) : 특수폴더 값을 파라미터로 전달
 +  * Environment.SpecialFolder.<xxxx> : <xxxx> 에 입력하려는 특수 폴더 상수 값
 +  * [[http://msdn.microsoft.com/ko-kr/library/system.environment.specialfolder.aspx|Environment.SpecialFolder 도움말]]
 +
 +<code csharp>
 +{
 +  Console.WriteLine( "GetFolderPath : {0}", 
 +    Environment.GetFolderPath( Environment.SpecialFolder.System ) );
 +}
 +</code>
 +
 +====== Text IO ======
 +
 +  * [[http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx|HowTo: Write Text to File]]
 +
 +===== File.AppendText Method로 스트링 Append =====
 +
 +[[http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx|File.AppendText Method]]
 +
 +파일을 만들고, 쓰기까지 좋은 예제
 +
 +<code csharp>
 +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);
 +    }
 +    }
 +  }
 +}
 +</code>
 +====== Binary IO ======
 +====== Control ======
 +
 +===== TextBox 에서 멀티라인 =====
 +
 +<code csharp>
 +// 총 몇줄인지 확인하기 위해서 쓴 코드
 +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 );
 +</code>
 +
 +===== 버튼상태조정 =====
 +
 +<code csharp>
 +SampleButton.Enabled = false; // true면 활성화
 +</code>
 +
 +====== System ======
 +
 +===== 프로세스 체크 =====
 +
 +<code csharp>
 +// 예제 프로그램에서 프로세스 이름을 구한다.
 +// 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;
 +</code>
 +
 +===== 프로세스실행 =====
 +<code csharp>
 +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;
 +}
 +</code>
 +
 +====== 압축 ======
 +
 +**System.IO.Compression** 과 **FileStream**/**MemoryStream**을 사용해서 파일 또는 메모리 압축/해제 하는 예제.
 +
 +파일에 대한 예제는 MSDN에 있으니 그쪽을 보자. [[http://msdn.microsoft.com/ko-kr/library/system.io.compression.deflatestream.aspx|DeflateStream]]
 +
 +<code csharp>
 +using System.IO.Compression;
 +</code>
 +
 +압축/압축풀기 코드
 +  * 참고한 URL [[http://stackoverflow.com/questions/4158942/deflatestream-not-decompressing-data-the-first-time|DeflateStream not decompressing data (the first time)]]
 +
 +<code csharp>
 +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) );
 +}
 +</code>
 +
 +
 +====== 랜덤 ======
 +
 +  * [[http://msdn.microsoft.com/en-us/library/system.random.aspx|System.Random]]
 +
 +<code csharp>
 +// 0~n사이의 랜덤 얻기
 +Random _rnd = new Random();
 +int _idx = _rnd.Next( 0, 100 ); // 0 ~ 100 사이의 랜덤 수 얻기
 +</code>
 +
 +====== 시간 (TimeDate) ======
 +
 +로그 출력용 시간 정보 얻기
 +
 +<code csharp>
 +using system;
 +DateTime saveNow = DateTime.Now;
 +string dtString = saveNow.ToString(@"yy/MM/dd hh:mm:ss.ffff");
 +
 +string _finalStr = String.Format("[{0}] {1}", dtString, "무언가 스트링");
 +</code>
 +
 +
 +====== Debug ======
 +
 +디버그용 메시지 출력
 +
 +<code csharp>
 +using System.Diagnostics;
 +
 +Debug.WriteLine("디버그 메시지 출력");
 +</code>
 +====== 그외 ======
 +
 +===== 실행 중인 프로그램 이름 얻기 =====
 +
 +<code csharp>
 +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
 +</code>
 +
 +===== 배열 =====
 +
 +2차 배열을 사용할때, 각 N 차 배열의 개수를 얻고 싶을때
 +
 +<code csharp>
 +//
 +int int_array[,] = new int[3,3]; // 3x3 배열을 만든 다음,
 +
 +// 0번째 배열 길이를 얻고 싶으면
 +int_array.GetLength( 0 ); // 요 함수로 얻는다.
 +</code>