반응형 C#82 빌드시 bin 폴더로 리소스(이미지 등) 복사하기, 출력 디렉터리로 복사 image 폴더의 파일을 빌드시 bin 폴더로 옮기고 싶다면해당 파일을 선택하고 Alt + Enter 또는 마우스 오른족 클릭하여 속성을 본다. 속성을 보면 출력 디렉터리로 복사 가 있다. 여기를 변경하면된다.옵션은 복사 '안함', '항상 복사', '변경된 내용만 복사'가 있다. 그럼 다음과 같이 해당 폴더와 파일이 복사가 된다. 2016. 1. 18. dll, exe가 있는 경로 알기 아래 코드는 dll 파일이 있는 경로를 가지고 와서 해당 경로 밑의 image 폴더의 "title bar.JPG" 이미지를 불러온다. using System.IO; using System.Reflection; string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string path = Path.Combine(exePath, "image"); string filePath = Path.Combine(path, "title bar.JPG"); Image img; if (File.Exists(filePath)) img = Image.FromFile(filePath); 2016. 1. 18. .NET Assembly Obfuscation(난독화) .NET Assembly Obfuscation 소스코드 난독화는 C++, 자바, C#등의 프로그램의 소스코드를 알아보기 힘든 형태로 바꾸는 기술이고, 바이너리 난독화는 컴파일 후에 생성된 바이너를 역공학을 통해 분석하기 힘들게 변조하는 기술이다.-http://guagua.egloos.com/m/4182996- 참고 사이트-바이너리 난독화http://guagua.egloos.com/m/4182996 상용 툴Secure team's obfuscatorCrypto Obfuscator http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm 공개 툴 http://confuser.codeplex.com/ 공개툴이지만 성능은 괜찮은 것 같다. 아래가 난독화 작업후의 소.. 2016. 1. 11. RSACryptoServiceProvider 암호화 RSACryptoServiceProvider 암호화 public static string Encrypt(this string target, string key) { if (string.IsNullOrEmpty(target)) throw new ArgumentException("target null"); if (string.IsNullOrEmpty(key)) throw new ArgumentException("key null"); return BitConverter.ToString( new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = key }) { PersistKeyInCsp = true }.Encrypt(Encoding.UTF8.. 2016. 1. 8. Regex 정규식 정규식 URL public static bool IsValidUrl(this string url) { return new Regex("^(https?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z](\\.[a-z]{2,6})?)(:[0-9]{1,5})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$").IsMatch(url); } GUID public static bool IsGuid(this string s) { if (s == null) throw new Ar.. 2016. 1. 8. 들어오는 메시지의 최대 메시지 크기 할당량(65536)을 초과했습니다. 할당량을 늘리려면 적합한 바인딩 요소에서 MaxReceivedMessageSize 속성을 사용하십시오. 들어오는 메시지의 최대 메시지 크기 할당량(65536)을 초과했습니다. 할당량을 늘리려면 적합한 바인딩 요소에서 MaxReceivedMessageSize 속성을 사용하십시오. 서비스 호출시 파일이나 전송되는 데이터의 양이 기본 활당양에 비해 클 때 발생한다. 해결은 client쪽의 config 파일을 다음을 추가한다. 2016. 1. 8. byte로 파일 쓰기(write byte to file) byte를 파일로 저장하기 1.FileStream 사용시 FileStream fs = new FileStream("file path", FileMode.OpenOrCreate, FileAccess.Write); byte[] file = (byte[])ds.Tables[0].Rows[0]["file"]; fs.Write(file, 0, file.Length); fs.Close(); 2.File 사용시 byte[] data = (byte[])ds.Tables[0].Rows[0]["PDF"]; File.WriteAllBytes(@"D:\Project\test.pdf", data); File.SetLastWriteTime(strFullName, tmLastWriteTime); // 마지막 작성일자를 임의 날짜로.. 2016. 1. 4. byte로 파일 읽기 파일을 byte로 읽어 들인다. using System.IO; using System.Runtime.Serialization.Formatters.Binary; FileStream fs = null; byte[] rtnByte = null; fs = new FileStream(@"D:\01.Source\testData.mp3", FileMode.Open, FileAccess.Read); rtnByte = new BinaryReader(fs).ReadBytes((int)fs.Length); 2015. 12. 29. 시스템 시작 혹은 중간에 강제로 디버깅 하고 싶을 때 프로그램 실행중 특정 위치에서 디버깅을 걸고 싶을 때 다음 코드를 추가하면 해당 부분을 수행 할 때 디버깅 할거냐고 다이얼로그 창이 뜬다. 하기 싫으면 안하면 되고, 걸고 싶다면 디버깅을 하면 된다. System.Diagnostics.Debugger.Launch(); 2015. 12. 24. ftp에서 파일 다운로드 하기(ftp file download) FTP file download FTP 접속하여 파일을 내려받는 코드는 다음만 있으면 된다. Uri ftpUri = new Uri(strDownloadPath); using (WebClient wc = new WebClient()) { wc.BaseAddress = strDownloadPath; wc.Credentials = new NetworkCredential(_ftpUser, _ftpPassword); wc.DownloadFileAsync(ftpUri, downloadPath);//비동기 wc.DownloadFile(ftpUri, localPath);//동기 } 아래 코드는 응용 코드. using System; using System.Collections.Generic; using System.Li.. 2015. 12. 23. text file에 텍스트 추가하기(File.AppendText) text file 전체을 읽어오지 않고 라인 단위로 글을 추가한다. string filePath = @"D:\05.work\FtpDownload\testtext.txt"; using (var sw = (!File.Exists(filePath) ? File.CreateText(filePath) :File.AppendText(filePath))) { sw.WriteLine(msg); } 2015. 12. 23. Stopped working CLR20r3 error 개발pc에서는 정상으로 작동이 되나 사용자에게 배포 후에 실행을 하였더니 다음과 같은 오류가 발생하였다. 구글링에 별의별 짓을 다 해봤지만... 원인은 알 수가 없었다.플랫폼변경하여 디버깅, 다른pc에서 빌드, 파일의 재배포 등등구글링 결과 이와 같은 문제를 격는 사람이 많은 것 같았다. 사용자 pc에서j 메세지를 가져올 수 없어 사진 찍어서 가져왔다. 구글링해서 찾은 비슷한 에러 메세지 문구. Stopped workingProblem signature:Problem Event Name: CLR20r3Problem Signature 01: XXXXXXXXXXX.exeProblem Signature 02: 1.0.0.1Problem Signature 03: 4f338fd9Problem Signature 0.. 2015. 12. 22. Application.DoEvents() Application.DoEvents();현재 메시지 큐에 있는 모든 Windows 메시지를 처리합니다. 응용프로그램을 만들고 폼의 빠른 업데이트를 화면을 보고 싶을때.버퍼에 쌓여 있는 처리내용을 강제로 뿌려주는 명령어 입니다. MSDN : 설명 Windows Form을 실행하는 경우 새 폼이 만들어진 다음, 이벤트가 처리될 때까지 대기합니다. 폼에서 이벤트를 처리할 때마다 해당 이벤트와 관련된 모든 코드가 처리됩니다. 다른 모든 이벤트는 큐에서 대기합니다. 코드에서 이벤트를 처리하는 동안 응용 프로그램은 응답하지 않습니다. 예를 들어, 다른 창을 해당 창의 위쪽으로 끌 때 해당 창은 다시 그려지지 않습니다.코드에서 DoEvents를 호출하면 응용 프로그램에서는 다른 이벤트를 처리할 수 있습니다. 예를 .. 2015. 11. 4. DataSet의 데이터 DB 저장시 수정, 삭제, 신규 구분하는 방법 Dataset에서 변경 된 데이터를 저장 할 때 biz에서 각 행별로 변경의 종류에 따라서 분기하여 처리 변수 생성 시기 이후로 변경된 데이터의 복사 본을 가져온다. _dsDeptVessel.DataSet.GetChanges(); foreach (DataRow row in data.DataSet.Tables[0].Rows){ if (row.RowState == DataRowState.Added) dac.InsertMTA550(row, data.Hashtable["UserID"].ToString()); else if (row.RowState == DataRowState.Deleted) dac.DeleteMTA550(row, data.Hashtable["UserID"].ToString());} 변경된 데이터.. 2015. 9. 4. 윈도우 인증 사용하여 DB 접속 윈도우 인증을 사용하여 DB에 접속 할 때 DB Connection string에 다음을 추가한다. Integrated Security=SSPI 윈도우 인증 DB접근 https://msdn.microsoft.com/en-us/library/ff647396.aspx http://stackoverflow.com/questions/18605533/connecting-to-sql-server-using-windows-authentication 2015. 8. 31. DateTime 날짜 유효성 검사. Datetime형 날짜가 유효한지 체크 할 때 다음과 같이 사용한다. var formats = new[] { "yyyyMMdd", "yyyy-MM-dd" }; DateTime dtRtn;if (!DateTime.TryParseExact("20140541", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtRtn)) { MsgCodeHelper.ShowDialog("AC0070", "입력된 날짜가 잘못되었습니다."); return; } 2015. 8. 31. using 키워드 2번 사용 사용 예 using 키워드를 다중해서 사용해야될 때 using안에 using이 아닌 다음과 같이 코딩하면 된다. using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. }using (var sr = new StringReader(content)) using (var xtr = new XmlTextReader(sr)) { obj = XmlSerializer.Deserialize(xtr) as TModel; } 2015. 8. 31. Windows Services 전용뷰어 보기 참조 MSDNhttp://msdn.microsoft.com/ko-kr/library/zt39148a(v=vs.110).aspx 순서1.프로젝트 생성2.코딩3.등록 installutil.exe mynewservice.exe4.삭제 installutin.exe /u mynewservice.exe5.디버깅 프로세스 잡아서 실행 타이머등등 활용해야됨. 2015. 8. 31. System.Data.OracleClient 사용하여 Oracle 연결 참고 사이트oracle client http://www.csharpstudy.com/Practical/Prac-oracle.aspx http://h5bak.tistory.com/88 2015. 8. 31. System.IO.DIrectory Directory 관련하여 생성, 삭제, 이동에 관련된 각각의 샘플 코드 CreateDirectory(System.String)using System; using System.IO;public class Program { public static void Main() { string path = @"C:\tijdelijk"; try { if (Directory.Exists(path)) { Console.WriteLine("The directory {0} already exists.", path); } else { Directory.CreateDirectory(path); Console.WriteLine("The directory {0} was created.", path); } } catch (Excep.. 2015. 8. 31. 파일 복사 이동 http://msdn.microsoft.com/ko-kr/library/cc148994.aspx방법: 파일 및 폴더 복사, 삭제 및 이동(C# 프로그래밍 가이드)public class SimpleFileCopy { static void Main() { string fileName = "test.txt"; string sourcePath = @"C:\Users\Public\TestFolder"; string targetPath = @"C:\Users\Public\TestFolder\SubDir"; // Use Path class to manipulate file and directory paths. string sourceFile = System.IO.Path.Combine(sourcePath, fileN.. 2015. 8. 26. File 관련 경로가 포함된 파일 문자열에서 파일명, 확장자 가져오기 -------------------------------------------------------------------------------------- var filename = txtFile.EditValue.x_AsString(); var fileNm = System.IO.Path.GetFileName(filename);//파일 이름 가져오기 var extention = System.IO.Path.GetExtension(filename).ToLower();//파일 확장자 가져오기 -------------------------------------------------------------------------------------- 이미지 파.. 2015. 8. 26. txt 파일 불러오기 txt 파일 읽어오기 소스... protected List TextFileToList() { var lst = new List(); var dlg = new OpenFileDialog(); dlg.Multiselect = false; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { byte[] line = System.IO.File.ReadAllBytes(dlg.FileName); string base64String = Convert.ToBase64String(line); byte[] bytes = Convert.FromBase64String(base64String); string fileTxt = Encoding.Default.GetSt.. 2015. 8. 26. String 메서드 응용 PadRight PadLeft 일정 크기의문자열에 빈공간을 지정한 문자로 채우고자 할 때 사용한다."33".PadLeft(7, '0'); -->0000033 특정문자(\\와 같은)로 일정 주기로 되어 잇는 문자열에서 마지막 것만 가져올 때f.Split('\\').Last() Contains 활용string[] enabledEditingColumsn = { "A", "B", "C" };if(enabledEditingColumsn.Contains(fieldName)) { 액션 } 2015. 8. 26. DataTable에서 유용하게 사용 되는 것들 DB저장시 널인지 체크 row["aaaa"] == DBNull.Value ? null : ((DateTime)row["aaaa"]).ToString("yyyyMMdd") -------------------------------------------------------------------------------------- 최대값 구하기DataTable의 int형 컬럼에 null 입력하기 ds.Tables[0].Columns["COLNM"].AllowDBNull = true; //안해도 될 것 같은데 혹시 몰라서 DataRow newRow; newRow["COLNM"] = A == B ? 123 : DBNull.Value; ---------------------------------------------.. 2015. 8. 26. LinQ List lnq = (from c in Competitor where c.FS_STARTER_VALUE == "Y" select c); -------------------------------------------------------------------------------------- DaTablevar dtCnt1 = (from row in dtPrintCnt1.AsEnumerable() where row.Field("CD") == changeDt.Rows[i]["_CD1"].x_AsString() && row.Field("RPT") != changeDt.Rows[i]["Cnt1"].x_AsString() select row); bindTable.AsEnumerable().GroupBy(r => .. 2015. 8. 26. yyyyMMdd 형식의 문자열을 DateTime으로 변경 해야될 때 'yyyyMMdd'형식으로 된 날짜 데이터를 DateTime으로 변경할 때에는 DateTime date = DateTime.ParseExact("20150826" , "yyyyMMdd", null); 국가별로 날짜를 표시하는 방법이 다르다. 그러므로 국가별로 사용 할 때는 각 국가에 맞는 CultureInfo를 사용하면 된다. DateTime date = DateTime.ParseExact("2015/08/26" , "yyyyMMdd" , new System.Globalization.CultureInfo("en-US")); 2015. 8. 26. Action및 delegate //action private void OpenDialog(OnsUserControlBase control, Action callback) { using (_popup = new HostWindow(control)) { _popup.ShowDialog(); _popup.Closed += (o, args) => { if (_popup.DialogResult == DevExpress.Xpf.Core.DialogResult.OK && callback != null) callback(); }; } } //delegate dt.ColumnChanged += delegate(object sender, DataColumnChangeEventArgs e) { GridView bandView = gridControl.M.. 2015. 8. 26. Activator.CreateInstance 동적으로 인스턴스 생성 텝으로 구성된 페이지에서 각 텝마다 팝업페이지가 다를 경우 다음과 같이 Activator.CreateInstance를 사용하여 간단하게 코딩할 수 있다. private Type OnsUserControlType(int tabIndex){ return tabIndex.Equals(0) ? typeof(BQ1031E) : tabIndex.Equals(1) ? typeof(BQ1032E) : tabIndex.Equals(2) ? typeof(BQ1033E) : typeof(OnsUserControlBase);} private OnsUserControlBase GetNewForm(int tabIndex) { var t = OnsUserControlType(tabIndex); return (OnsUserContr.. 2015. 8. 26. 정규식 전화번호 밸리데이션 \d{2,3}-\d{3,4}-\d{4} 2015. 8. 26. 이전 1 2 3 다음 반응형