language:csharp:코드-조각
차이
문서의 선택한 두 판 사이의 차이를 보여줍니다.
양쪽 이전 판이전 판다음 판 | 이전 판 | ||
language:csharp:코드-조각 [2016/02/21 18:55] – [String : Format] kieuns | language:csharp:코드-조각 [2024/04/23 22:44] (현재) – 바깥 편집 127.0.0.1 | ||
---|---|---|---|
줄 1: | 줄 1: | ||
+ | {{htmlmetatags> | ||
+ | metatag-keywords=(C#, | ||
+ | metatag-description=(C# | ||
+ | }} | ||
+ | C# 코드 모음 | ||
+ | |||
+ | {{tag> | ||
+ | |||
+ | ====== 빈도 높은 ====== | ||
+ | |||
+ | ===== MessageBox ===== | ||
+ | [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | MessageBox.Show( messageString, | ||
+ | </ | ||
+ | |||
+ | ===== Assert ===== | ||
+ | |||
+ | <code csharp> | ||
+ | using System.Diagnostics; | ||
+ | |||
+ | Debug.Assert( < | ||
+ | </ | ||
+ | ===== 가변인자 ===== | ||
+ | |||
+ | <code csharp> | ||
+ | string s; | ||
+ | s = System.String.Format( "{0} times {1} = {2}", i, j, (i * j) ); | ||
+ | </ | ||
+ | |||
+ | |||
+ | ===== String ===== | ||
+ | |||
+ | ==== string to byte 변환 ==== | ||
+ | |||
+ | <code csharp> | ||
+ | string _dataStr = @" | ||
+ | // StringBuilder에 집어 넣은 다음 | ||
+ | StringBuilder builder = new StringBuilder( _dataStr ); | ||
+ | // 원하는 캐릭터를 변경하고 | ||
+ | builder[0] = (char)((int)builder[0] + 4); | ||
+ | // 다시 스트링에 집어 넣는다. | ||
+ | _dataStr = builder.ToString(); | ||
+ | </ | ||
+ | |||
+ | ==== 스트링 조합 ==== | ||
+ | |||
+ | [[http:// | ||
+ | |||
+ | 조합 스트링의 기본 | ||
+ | <code csharp> | ||
+ | string output = string.Format(" | ||
+ | </ | ||
+ | 나머지 상세 내용은 링크 참조. | ||
+ | |||
+ | ====== String : Format ====== | ||
+ | |||
+ | - 합성 형식 지정: http:// | ||
+ | - 표준 숫자 서식 문자열: http:// | ||
+ | - 사용자 지정 숫자 서식 문자열: http:// | ||
+ | |||
+ | ===== ToString()에서 소수점 자리수 조정 ===== | ||
+ | |||
+ | ToString()만으로 소수점 자리수를 잘라서 표시하기. | ||
+ | |||
+ | <code csharp> | ||
+ | float a1 = 0.12345f; | ||
+ | string _msg1 = a1.ToString(" | ||
+ | string _msg2 = a1.ToString(" | ||
+ | </ | ||
+ | |||
+ | ===== 서식 문자열 기본 사용 ===== | ||
+ | |||
+ | <code csharp> | ||
+ | string output = string.Format(" | ||
+ | </ | ||
+ | |||
+ | {0} : 첫번째 파라미터를 그대로 반영한다. | ||
+ | |||
+ | {1,3:D} : 두번째 파라미터를 받는다. | ||
+ | * ', | ||
+ | * ': | ||
+ | |||
+ | <code csharp> | ||
+ | string output = string.Format(" | ||
+ | // 결과: 021 | ||
+ | </ | ||
+ | |||
+ | * {0 : 포맷 파라미터 인덱스. | ||
+ | * : : 파라미터 연장 | ||
+ | * D3 : D는 정수입력이라는 뜻이고, 3은 자리수가 3자리. 빈자리에는 0을 채운다. | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | ===== 포맷 문자열 형식 변환 ===== | ||
+ | |||
+ | |||
+ | <code csharp> | ||
+ | ( " | ||
+ | ( " | ||
+ | ( " | ||
+ | ( " | ||
+ | ( " | ||
+ | |||
+ | ( " | ||
+ | |||
+ | ( " | ||
+ | ( " | ||
+ | </ | ||
+ | |||
+ | |||
+ | ===== str to int ===== | ||
+ | |||
+ | 자주 잊어버리는데.. ( [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | using System; // 네임스페이스를 포함시키려면 | ||
+ | |||
+ | string str_num = " | ||
+ | int nv = System.Convert.ToInt32(str_num); | ||
+ | // or | ||
+ | nv = Int32.Parse(str_num); | ||
+ | </ | ||
+ | |||
+ | ===== char to int ===== | ||
+ | |||
+ | <code csharp> | ||
+ | string numberStr = " | ||
+ | char[] num_char_ar = numberStr.ToCharArray(); | ||
+ | for( int i = 0; i < num_char_ar.Length; | ||
+ | { | ||
+ | // 리턴값 형식이 double이라 강제 형변환 | ||
+ | int nv = (int)System.Char.GetNumericValue(num_char_ar[i]); | ||
+ | } | ||
+ | </ | ||
+ | ====== Directory IO ====== | ||
+ | |||
+ | ===== LINK ===== | ||
+ | |||
+ | * [[http:// | ||
+ | * [[http:// | ||
+ | * [[http:// | ||
+ | |||
+ | ===== Example ===== | ||
+ | |||
+ | ====디렉토리 있는지 검사==== | ||
+ | |||
+ | <code csharp> | ||
+ | using System.IO; | ||
+ | // log 폴더가 없으면 만든다. | ||
+ | if(!Directory.Exists(" | ||
+ | Directory.CreateDirectory(" | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ====특정 폴더의 파일과 서브 폴더 이름을 모두 읽어 오는 간단한 예제==== | ||
+ | |||
+ | <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(" | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | 조건을 붙여 필요한 파일이나 폴더 목록을 받아오는 방법 - 우선 링크만 | ||
+ | |||
+ | * [[https:// | ||
+ | |||
+ | ====== File IO ====== | ||
+ | |||
+ | * [[http:// | ||
+ | |||
+ | ===== File Exist ===== | ||
+ | <code csharp> | ||
+ | using System; | ||
+ | using System.IO; | ||
+ | |||
+ | class Test | ||
+ | { | ||
+ | public static void Main() | ||
+ | { | ||
+ | string sourceFile = @" | ||
+ | string newFile = @" | ||
+ | if (File.Exists(sourceFile)) { | ||
+ | File.Copy(sourceFile, | ||
+ | } | ||
+ | else { | ||
+ | Console.WriteLine(" | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ===== Path의 사용 ===== | ||
+ | |||
+ | using System.IO; | ||
+ | |||
+ | * [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | String samplePath = @" | ||
+ | // return " | ||
+ | String targetProcName = Path.GetFileNameWithoutExtension( samplePath ).ToUpper(); | ||
+ | |||
+ | // return " | ||
+ | Path.GetDirectoryName( samplePath ); | ||
+ | </ | ||
+ | |||
+ | msdn 봐도 되지만 여기서 찾고 끝내는 함수. | ||
+ | |||
+ | | GetDirectoryName(String) | 경로를 리턴 | | ||
+ | | GetExtension(String) | 확장자만 리턴 | | ||
+ | | GetFileName(String) | 경로명에서 이름과 확장자를 리턴 | | ||
+ | | GetFileNameWithoutExtension(String) | 파일 이름만 리턴 | | ||
+ | |||
+ | ===== Directory 의 사용 ===== | ||
+ | <code csharp> | ||
+ | String samplePath = @" | ||
+ | if( Directory.Exists( samplePath ) ) | ||
+ | Directory.SetCurrentDirectory( samplePath ); | ||
+ | </ | ||
+ | |||
+ | ===== 특수한 폴더 경로 ===== | ||
+ | |||
+ | * Environment.GetFolderPath(< | ||
+ | * Environment.SpecialFolder.< | ||
+ | * [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | { | ||
+ | Console.WriteLine( " | ||
+ | Environment.GetFolderPath( Environment.SpecialFolder.System ) ); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ====== Text IO ====== | ||
+ | |||
+ | * [[http:// | ||
+ | |||
+ | ===== File.AppendText Method로 스트링 Append ===== | ||
+ | |||
+ | [[http:// | ||
+ | |||
+ | 파일을 만들고, 쓰기까지 좋은 예제 | ||
+ | |||
+ | <code csharp> | ||
+ | using System; | ||
+ | using System.IO; | ||
+ | |||
+ | class Test | ||
+ | { | ||
+ | public static void Main() | ||
+ | { | ||
+ | string path = @" | ||
+ | // 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(" | ||
+ | sw.WriteLine(" | ||
+ | sw.WriteLine(" | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // This text is always added, making the file longer over time | ||
+ | // if it is not deleted. | ||
+ | using (StreamWriter sw = File.AppendText(path)) | ||
+ | { | ||
+ | sw.WriteLine(" | ||
+ | sw.WriteLine(" | ||
+ | sw.WriteLine(" | ||
+ | } | ||
+ | | ||
+ | // 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 에서 멀티라인 ===== | ||
+ | |||
+ | <code csharp> | ||
+ | // 총 몇줄인지 확인하기 위해서 쓴 코드 | ||
+ | char[] _zsp = new char[] { ' | ||
+ | String[] logs = mLogView.Text.Split( _zsp ); | ||
+ | |||
+ | if( logs.Length > maxLogLineCount ) | ||
+ | mLogView.ResetText(); | ||
+ | |||
+ | // Environment.NewLine를 붙여주면 줄 바꾸기가 된다. | ||
+ | mLogView.AppendText( newLog + Environment.NewLine ); | ||
+ | </ | ||
+ | |||
+ | ===== 버튼상태조정 ===== | ||
+ | |||
+ | <code csharp> | ||
+ | SampleButton.Enabled = false; // true면 활성화 | ||
+ | </ | ||
+ | |||
+ | ====== 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 csharp> | ||
+ | public bool StartProcess() | ||
+ | { | ||
+ | // default value : @" | ||
+ | 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.Compression** 과 **FileStream**/ | ||
+ | |||
+ | 파일에 대한 예제는 MSDN에 있으니 그쪽을 보자. [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | using System.IO.Compression; | ||
+ | </ | ||
+ | |||
+ | 압축/ | ||
+ | * 참고한 URL [[http:// | ||
+ | |||
+ | <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 = @" | ||
+ | string _midBuffer = Base64Compress( _beforeComp ); | ||
+ | string _resultStr = Decompress( Convert.FromBase64String(_midBuffer) ); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | |||
+ | ====== 랜덤 ====== | ||
+ | |||
+ | * [[http:// | ||
+ | |||
+ | <code csharp> | ||
+ | // 0~n사이의 랜덤 얻기 | ||
+ | Random _rnd = new Random(); | ||
+ | int _idx = _rnd.Next( 0, 100 ); // 0 ~ 100 사이의 랜덤 수 얻기 | ||
+ | </ | ||
+ | |||
+ | ====== 시간 (TimeDate) ====== | ||
+ | |||
+ | 로그 출력용 시간 정보 얻기 | ||
+ | |||
+ | <code csharp> | ||
+ | using system; | ||
+ | DateTime saveNow = DateTime.Now; | ||
+ | string dtString = saveNow.ToString(@" | ||
+ | |||
+ | string _finalStr = String.Format(" | ||
+ | </ | ||
+ | |||
+ | |||
+ | ====== Debug ====== | ||
+ | |||
+ | 디버그용 메시지 출력 | ||
+ | |||
+ | <code csharp> | ||
+ | using System.Diagnostics; | ||
+ | |||
+ | Debug.WriteLine(" | ||
+ | </ | ||
+ | ====== 그외 ====== | ||
+ | |||
+ | ===== 실행 중인 프로그램 이름 얻기 ===== | ||
+ | |||
+ | <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: | ||
+ | // 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차 배열을 사용할때, | ||
+ | |||
+ | <code csharp> | ||
+ | // | ||
+ | int int_array[, | ||
+ | |||
+ | // 0번째 배열 길이를 얻고 싶으면 | ||
+ | int_array.GetLength( 0 ); // 요 함수로 얻는다. | ||
+ | </ |