ASP.NET Web API 반환 데이터 XML 형식 제거(JSON 형태로 데이터 반환)
MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API
In Global.asax add the line:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();like so:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}'C#' 카테고리의 다른 글
| 폴더 압축 (SharpZipLib 사용) (0) | 2017.11.28 |
|---|---|
| ClosedXML 사용 (0) | 2017.05.17 |
| ASP.NET 엑셀 출력 스타일 (0) | 2016.08.31 |
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
폴더 압축 (SharpZipLib 사용)
* 특정 폴더에 있는 파일 압축
* ICSharpCode.SharpZipLib.dll 사용
* folderPath : 폴더 경로(서버 물리 경로)
public void DownloadZipFile(string folderPath)
{
if (Directory.Exists(folderPath))
{
var zipFilePath = string.Format("{0}.zip", folderPath);
//-----------------------------------
//파일 압축
//-----------------------------------
try
{
var files = Directory.GetFiles(folderPath);
// 'using' statements guarantee the stream is closed properly which is a big source
// of problems otherwise. Its exception safe as well which is great.
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9); // 0 - store only to 9 - means best compression
byte[] buffer = new byte[4096];
foreach (string file in files)
{
// Using GetFileName makes the result compatible with XP
// as the resulting path is not absolute.
var entry = new ZipEntry(Path.GetFileName(file));
// Setup the entry data as required.
// Crc and size are handled by the library for seakable streams
// so no need to do them here.
// Could also use the last write time or similar for the file.
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
// Using a fixed size buffer here makes no noticeable difference for output
// but keeps a lid on memory usage.
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
// Finish/Close arent needed strictly as the using statement does this automatically
// Finish is important to ensure trailing information for a Zip file is appended. Without this
// the created file would be invalid.
s.Finish();
// Close is important to wrap things up and unlock the file.
s.Close();
}
}
catch
{
throw new Exception("파일을 압축하는 도중 오류가 발생하였습니다.");
}
//-----------------------------------
//폴더 삭제
//-----------------------------------
try
{
Directory.Delete(folderPath, true);
}
catch
{
throw new Exception("압축폴더를 다운로드 하는 도중 오류가 발생하였습니다.");
}
//-----------------------------------
//압축파일 다운로드
//-----------------------------------
try
{
this.DownloadZipFile(zipFilePath, true);
}
catch
{
throw new Exception("압축파일을 다운로드 하는 도중 오류가 발생하였습니다.");
}
}
}
* DownloadZipFile() 서버의 압축파일(ZIP)을 다운로드한다.
////// 서버의 압축파일(ZIP)을 다운로드한다. /// /// 서버 파일 경로 /// 다운로드 후 파일 삭제여부 public void DownloadZipFile(string filePath, bool deleteAfterDown) { var fileName = System.IO.Path.GetFileName(filePath); //한글 깨어짐 방지 var saveFileName = HttpUtility.UrlEncode(fileName).Replace("+", "%20"); var response = System.Web.HttpContext.Current.Response; //아래 방식을 사용하면 다운로드 후 압축파일이 깨어졌다는 메시지 표시 /* response.ClearContent(); response.Clear(); response.ContentType = "application/zip"; response.Charset = "utf-8"; response.AddHeader("Content-Disposition", "attachment; filename=" + saveFileName + ";"); response.TransmitFile(filePath); response.Flush(); if (deleteAfterDown) { //파일 삭제 var deleteFile = new System.IO.FileInfo(filePath); if (deleteFile.Exists) { System.IO.File.Delete(filePath); } } response.End(); */ //--------------------------------------------- //제네릭 처리기 사용 //--------------------------------------------- //Response.TransmitFile() 메소드 사용시 압축파일이 깨졌다는 메시지 표시 response.Redirect(string.Format("~/DownloadZipFile.ashx?fileName={0}", saveFileName)); }
* DownloadZipFile.ashx 파일 내용
<%@ WebHandler Language="C#" Class="DownloadZipFile" %>
using System;
using System.IO;
using System.Web;
public class DownloadZipFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var request = context.Request;
var response = context.Response;
var fileName = request.QueryString["fileName"];
if (!string.IsNullOrEmpty(fileName))
{
var saveFileName = HttpUtility.UrlEncode(fileName).Replace("+", "%20");
var fullPath = string.Format("{0}{1}", context.Server.MapPath(@"~/Download/"), fileName); //다운로드 파일 경로
response.ClearContent();
response.Clear();
response.ContentType = "application/zip";
response.Charset = "utf-8";
response.AddHeader("Content-Disposition", string.Format(@"attachment; filename=""{0}"";", saveFileName));
response.TransmitFile(fullPath);
response.Flush();
//엑셀 파일 삭제
var deleteFile = new FileInfo(fullPath);
if (deleteFile.Exists)
{
File.Delete(fullPath);
}
response.End();
}
else
{
var script = "<script type='text/javascript'>alert('압축 파일을 찾을 수 없습니다.');history.back();</script>";
response.Write(script);
response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
'C#' 카테고리의 다른 글
| ASP.NET Web API 반환 데이터 XML 형식 제거(JSON 형태로 데이터 반환) (0) | 2017.12.22 |
|---|---|
| ClosedXML 사용 (0) | 2017.05.17 |
| ASP.NET 엑셀 출력 스타일 (0) | 2016.08.31 |
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
ClosedXML 사용
* AddWorksheet() 새로운 워크시트를 만든다.
public IXLWorksheet AddWorksheet(XLWorkbook wb, string sheetName)
{
var ws = wb.AddWorksheet(sheetName);
ws.Style.Font.SetFontName("맑은 고딕"); //기본글꼴
ws.Style.Font.SetFontSize(10); //기본글꼴크기
ws.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; //세로맞춤: 가운데
return ws;
}
* GetExcelColumn() 지정한 컬럼의 엑셀 컬럼문자를 가져온다.
public string GetExcelColumn(int columnIndex)
{
var colString = "";
if (columnIndex > 26)
{
var surplus = columnIndex % 26; if (surplus == 0) surplus = 26;
var quota = (columnIndex - surplus) / 26;
//3글자 컬럼명
if (quota > 26)
{
var surplus2 = quota % 26;
var quota2 = (quota - surplus2) / 26;
colString = string.Format("{0}{1}{2}", Convert.ToChar(64 + quota2), Convert.ToChar(64 + surplus2), Convert.ToChar(64 + surplus));
}
//2글자 컬럼명
else
{
colString = string.Format("{0}{1}", Convert.ToChar(64 + quota), Convert.ToChar(64 + surplus));
}
}
else
{
colString = string.Format("{0}", Convert.ToChar(64 + columnIndex));
}
return colString;
}
* AddExcelCell() 지정한 셀에 숫자값을 표시한다.
public IXLCell AddExcelCell(IXLWorksheet ws, int row, int col, int value, string bgColor
, bool bold, XLAlignmentHorizontalValues hAlign)
{
var cell = ws.Cell(row, col);
cell.SetValue(value);
cell.DataType = XLCellValues.Number;
cell.Style.NumberFormat.Format = "#,##0;(#,##0);-";
cell.Style.Alignment.Horizontal = hAlign;
cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
if (bold) cell.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(bgColor)) cell.Style.Fill.BackgroundColor = XLColor.FromHtml(bgColor);
return cell;
}
* AddExcelCell() 지정한 셀에 문자열을 표시한다.
public IXLCell AddExcelCell(IXLWorksheet ws, int row, int col, string value, string bgColor, bool bold
, XLAlignmentHorizontalValues hAlign, XLBorderStyleValues outsideBorder)
{
var cell = ws.Cell(row, col).SetValue(value);
cell.DataType = XLCellValues.Text;
cell.Style.Alignment.Horizontal = hAlign;
cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
cell.Style.Border.OutsideBorder = outsideBorder;
if (bold) cell.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(bgColor)) cell.Style.Fill.BackgroundColor = XLColor.FromHtml(bgColor);
return cell;
}
* AddExcelCell() 지정한 셀에 문자열을 표시하고 병합한다.
public IXLRange AddExcelCell(IXLWorksheet ws, int row, int col, int rowSpan, int colSpan, string value, string bgColor, int width)
{
var endRow = (rowSpan > 1) ? row + rowSpan - 1 : row;
var endCol = (colSpan > 1) ? col + colSpan - 1 : col;
var rg = ws.Range(row, col, endRow, endCol);
rg.Merge();
rg.Cell(1, 1).SetValue(value);
rg.DataType = XLCellValues.Text;
rg.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
rg.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
rg.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
if (!string.IsNullOrEmpty(bgColor)) rg.Style.Fill.BackgroundColor = XLColor.FromHtml(bgColor);
if (width > 0) rg.FirstCell().WorksheetColumn().Width = width;
return rg;
}
public IXLRange AddExcelCell(IXLWorksheet ws, int row, IXLRange range, int rowSpan, int colSpan, string value, string bgColor, int width)
{
var col = range.Cell(1, 1).WorksheetColumn().ColumnNumber() + range.ColumnCount();
var endRow = (rowSpan > 1) ? row + rowSpan - 1 : row;
var endCol = (colSpan > 1) ? col + colSpan - 1 : col;
var rg = ws.Range(row, col, endRow, endCol);
rg.Merge();
rg.Cell(1, 1).SetValue(value);
rg.DataType = XLCellValues.Text;
rg.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
rg.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
rg.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
if (!string.IsNullOrEmpty(bgColor)) rg.Style.Fill.BackgroundColor = XLColor.FromHtml(bgColor);
if (width > 0) rg.FirstCell().WorksheetColumn().Width = width;
return rg;
}
* AddExcelFormularCell() 지정한 셀에 엑셀 수식을 표시한다.
public IXLCell AddExcelFormularCell(IXLWorksheet ws, int row, int col, string formular, string bgColor, bool bold, string numberFormat)
{
var cell = ws.Cell(row, col);
if (!string.IsNullOrEmpty(formular))
{
cell.DataType = XLCellValues.Number;
if (!string.IsNullOrEmpty(numberFormat)) cell.Style.NumberFormat.Format = numberFormat;
cell.SetFormulaA1(formular);
}
cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
if (bold) cell.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(bgColor)) cell.Style.Fill.BackgroundColor = XLColor.FromHtml(bgColor);
return cell;
}
* DownloadExcel() 서버의 엑셀 파일을 다운로드한다.
////// 서버의 엑셀 파일을 다운로드한다. /// /// 실제 서버 물리 경로 /// 엑셀 파일명 public void DownloadExcel(string filePath, string fileName) { //한글 깨어짐 방지 var saveFileName = HttpUtility.UrlEncode(fileName).Replace("+", "%20"); //var fullPath = filePath + fileName; var response = System.Web.HttpContext.Current.Response; //--------------------------------------------------------------------- //엑셀 파일 다운로드 //--------------------------------------------------------------------- //서버의 엑셀 파일 다운로드 후 몇 바이트 늘어남 -> 엑셀 열기 선택 시 복구 메시지 표시 //--------------------------------------------------------------------- //response.ClearContent(); //response.Clear(); //response.Charset = "utf-8"; //response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); ////response.ContentType = "application/vnd.msexcel"; //response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //response.AddHeader("Content-Disposition", string.Format(@"attachment; filename=""{0}"";", saveFileName)); ////response.TransmitFile(Server.MapPath("/" + fileName)); //response.TransmitFile(fullPath); //response.Flush(); //엑셀 파일 삭제 //var deleteFile = new System.IO.FileInfo(fullPath); //if (deleteFile.Exists) //{ // System.IO.File.Delete(fullPath); //} //response.End(); //--------------------------------------------- //제네릭 처리기 사용 //--------------------------------------------- //열기 선택 시 엑셀 파일이 읽기 전용으로 열림 //--------------------------------------------- response.Redirect(string.Format("~/DownloadExcelFile.ashx?fileName={0}", saveFileName)); }다운로드 후에는 서버의 엑셀 파일을 삭제한다. ///
* DownloadExcelFile.ashx 파일 내용
<%@ WebHandler Language="C#" Class="DownloadExcelFile" %>
using System;
using System.IO;
using System.Web;
public class DownloadExcelFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var request = context.Request;
var response = context.Response;
var fileName = request.QueryString["fileName"];
if (!string.IsNullOrEmpty(fileName))
{
var saveFileName = HttpUtility.UrlEncode(fileName).Replace("+", "%20");
var fullPath = string.Format("{0}{1}", context.Server.MapPath(@"~/Download/"), fileName); //다운로드 경로
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", string.Format(@"attachment; filename=""{0}"";", saveFileName));
response.TransmitFile(fullPath);
response.Flush();
//엑셀 파일 삭제
var deleteFile = new FileInfo(fullPath);
if (deleteFile.Exists)
{
File.Delete(fullPath);
}
response.End();
}
else
{
var script = "<script type='text/javascript'>alert('엑셀 파일을 찾을 수 없습니다.');history.back();</script>";
response.Write(script);
response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
※ 사용방법
using(var wb = new new XLWorkbook())
{
var ws = AddWorksheet(wb, "Test Sheet");
var row = 1;
var col = 1;
for (var i = 0; i < list.Length; i++)
{
col = 1;
AddExcelCell(ws, row, col++, list[i]["COL1"].ToString());
AddExcelCell(ws, row, col++, list[i]["COL2"].ToString());
row++;
}
ws.Columns().AdjustToContents(); //열 너비 자동설정(데이터양이 많을 경우 속도가 매우 느려짐)
wb.SaveAs(@"d:\\example.xlsx"); //서버의 지정한 경로에 저장
DownloadExcel(@"d:\\example.xlsx"); //서버의 경로에 저장되므로 사용자는 다운로드 필요
}
※ 주의사항ws.Columns().AdjustToContents();
열 너비 자동설정하는 명령어인데 데이터양이 조금이라도 많을 경우 속도가 매우 느려지므로 조심해서 사용하자.
'C#' 카테고리의 다른 글
| ASP.NET Web API 반환 데이터 XML 형식 제거(JSON 형태로 데이터 반환) (0) | 2017.12.22 |
|---|---|
| 폴더 압축 (SharpZipLib 사용) (0) | 2017.11.28 |
| ASP.NET 엑셀 출력 스타일 (0) | 2016.08.31 |
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
ASP.NET 엑셀 출력 스타일
1. 기본 '텍스트 줄 바꿈' 속성 제외
기본 엑셀 출력 시 모든 셀에 '텍스트 줄 바꿈' 속성이 설정된다.
이를 방지하려면 아래와 같이 스타일을 설정한다.
<style type="text/css">
td { white-space:nowrap; }
</style>
2. 같은 셀에 2줄 표시
만약 특정 셀에서 같은 셀에 2줄 이상을 표시하고 싶을 때가 있다.
이럴 경우에는 아래와 같이 스타일을 설정한다.
<style type="text/css">
br { mso-data-placement:same-cell; }
</style>
Reponse.Write("<td>이번 셀에서는<br/>이 줄은 다음 줄에 표시</td>");
결과
이번 셀에서는
이 줄은 다음 줄에 표시
3. 기본 '텍스트 줄 바꿈' 속성 제외와 같은 셀 2줄 표시를 동시에 하고 싶은 경우
아래와 같이 스타일을 설정한다.
<style type="text/css">
td { white-space:nowrap; }
br { mso-data-placement:same-cell; }
.same { white-space:normal; }
</style>
Reponse.Write("<td>이번 셀에서는<br/>한 줄에 표시</td>");
Reponse.Write(@"<td class=""same"">이번 셀에서는<br/>이 줄은 다음 줄에 표시</td>");
결과
이번 셀에서는한 줄에 표시
이번 셀에서는
이 줄은 다음 줄에 표시
같은 셀에 2줄 이상 표시하려면 '텍스트 줄 바꿈' 속성이 설정되어야 하므로
원하는 셀에 same css를 설정하여 같은 셀에 표시할 수 있도록 해준다.
4. 숫자 형식 지정(자릿점 표시)
원하는 셀에 다음과 같이 스타일을 지정한다.
//number가 문자열인 경우에도 강제 지정
Response.Write(string.Format(@"<td style=""mso-number-format:'#,###';"">{0}</td>", number));
또는
//number가 숫자형식인 경우만 제대로 표시
Response.Write(string.Format("<td>{0:N0}"</td>, number));
5. 강제 문자열 형식 지정(숫자도 문자처럼 표시)
Response.Write(string.Format(@"<td style=""mso-number-format:'@';"">{0}</td>", string));
6. 한글 인코딩 설정
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
'C#' 카테고리의 다른 글
| 폴더 압축 (SharpZipLib 사용) (0) | 2017.11.28 |
|---|---|
| ClosedXML 사용 (0) | 2017.05.17 |
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
사진 이미지 관련 클래스
////// 사진 정보 /// public class PhotoInfo { private int maxWidth = 200, maxHeight = 267; private int orgWidth = 0, orgHeight = 0; private int width = 0, height = 0; private bool portraitMode = false; private string base64String = null; ////// 사진 정보 /// public PhotoInfo() { } ////// 사진 정보 /// /// public PhotoInfo(MemoryStream ms) { this.base64String = "data:image/jpg;base64," + Convert.ToBase64String(ms.ToArray()); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); this.orgWidth = img.Width; this.orgHeight = img.Height; this.portraitMode = (img.Height - img.Width) > 0; //세로가 긴 사진인 경우 if (this.portraitMode) { if (this.orgHeight > this.maxHeight) { this.height = this.maxHeight; var ratio = (this.maxHeight * 1.0) / (this.orgHeight * 1.0); this.width = (int)Math.Round(this.orgWidth * ratio); if (this.width > maxWidth) { this.width = maxWidth; ratio = (this.maxWidth * 1.0) / (this.orgWidth * 1.0); this.height = (int)Math.Round(this.orgHeight * ratio); } } else { this.height = this.orgHeight; this.width = this.orgWidth; if (this.width > maxWidth) { this.width = maxWidth; var ratio = (this.maxWidth * 1.0) / (this.orgWidth * 1.0); this.height = (int)Math.Round(this.orgHeight * ratio); } } } //가로가 긴 사진인 경우(LandscapeMode) else { if (this.orgWidth > this.maxWidth) { this.width = this.maxWidth; var ratio = (this.maxWidth * 1.0) / (this.orgWidth * 1.0); this.height = (int)Math.Round(this.orgHeight * ratio); if (this.height > maxHeight) { this.height = maxHeight; ratio = (this.maxHeight * 1.0) / (this.orgHeight * 1.0); this.width = (int)Math.Round(this.orgWidth * ratio); } } else { this.width = this.orgWidth; this.height = this.orgHeight; if (this.height > maxHeight) { this.height = maxHeight; var ratio = (this.maxHeight * 1.0) / (this.orgHeight * 1.0); this.width = (int)Math.Round(this.orgWidth * ratio); } } } } ////// 사진 최대 너비 /// public int MaxWidth { get { return maxWidth; } } ////// 사진 최대 높이 /// public int MaxHeight { get { return maxHeight; } } ////// 원본 사진 너비 /// public int OrgWidth { get { return this.orgWidth; } } ////// 원본 사진 높이 /// public int OrgHeight { get { return this.orgHeight; } } ////// 사진 너비 /// public int Width { get { return this.width; } } ////// 사진 높이 /// public int Height { get { return this.height; } } ////// 사진 가로방향여부 /// public bool PortraitMode { get { return this.portraitMode; } } ////// Base64 문자열 /// public string Base64String { get { return base64String; } } ////// 사진 정보 표시 /// /// public void SetImage(Image image) { if (this.Base64String != null) { image.ImageUrl = this.Base64String; image.Height = this.Height; image.Width = this.width; } } }
'C#' 카테고리의 다른 글
| ClosedXML 사용 (0) | 2017.05.17 |
|---|---|
| ASP.NET 엑셀 출력 스타일 (0) | 2016.08.31 |
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
| 윈도우에 등록된 확장자를 가진 파일 열기 (0) | 2011.11.16 |
오라클 BLOB 등록 및 조회
if (!fileUpload.HasFile)
{
Alert("업로드할 사진이 없습니다.");
Response.End();
}
var fileLength = fileUpload.PostedFile.ContentLength;
if (fileLength > 1024000)
{
Alert("1MB 이하의 사진만 업로드 할 수 있습니다.");
Response.End();
}
byte[] photoData = new byte[fileLength - 1];
photoData = fileUpload.FileBytes;
var userID = "";
var msg = "FAIL";
var query = "INSERT INTO PHOTO (USER_ID, PHOTO) VALUES ('{0}', :PHOTO)";
//var query = "UPDATE PHOTO SET PHOTO = :PHOTO WHERE USER_ID = '{0}'";
query = string.Format(query, userID);
try
{
using (var conn = new OracleConnect(connStr))
{
var cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
var param = cmd.Parameters.Add(":PHOTO", OracleType.Blob);
param.Direction = ParameterDirection.Input;
param.Value = photoData;
var result = cmd.ExecuteNonQuery();
if (result == 1)
{
msg = "SUCCESS";
}
}
}
catch (Exception ex)
{
throw ex;
}
'C#' 카테고리의 다른 글
| ASP.NET 엑셀 출력 스타일 (0) | 2016.08.31 |
|---|---|
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
| 윈도우에 등록된 확장자를 가진 파일 열기 (0) | 2011.11.16 |
| 날짜 문자열을 DateTime형으로 변환 (0) | 2011.10.27 |
다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기
try
{
//시작 프로젝트에 있는 리소스일 경우는 GetEntryAssembly()
//var assembly = System.Reflection.Assembly.GetEntryAssembly();
var assembly = System.Reflection.Assembly.Load("MyAssemplyName");
var res = new System.Resources.ResourceManager("MyNameSpace.Properties.Resources", assembly);
var image = Image.FromStream(res.GetStream("MyImageName"));
//리소스 파일에 있는 특정 문자열을 가져오려면
var text = res.GetString("MyResourceName", System.Globalization.CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
throw ex;
}
다른 프로젝트의 특정 폴더에 있는 이미지에 접근하려면try
{
var assembly = System.Reflection.Assembly.Load("MyAssemplyName");
var image = Image.FromStream(assembly.GetManifestResourceStream("MyNameSpace.MyFolderName.MyImageFileName"));
}
catch (Exception ex)
{
throw ex;
}
전체 리소스 이름을 알고 싶다면 다음 메소드를 사용한다.var list = System.Reflection.Assembly.Load("MyAssemplyName").GetManifestResourceNames();
foreach (var item in list)
{
...
}
'C#' 카테고리의 다른 글
| 사진 이미지 관련 클래스 (0) | 2016.04.14 |
|---|---|
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
| 윈도우에 등록된 확장자를 가진 파일 열기 (0) | 2011.11.16 |
| 날짜 문자열을 DateTime형으로 변환 (0) | 2011.10.27 |
| ComboBox SelectedItem (0) | 2011.10.27 |
윈도우에 등록된 확장자를 가진 파일 열기
간단하게
Process.Start(filePath);또는
private void OpenFile(string filePath)
{
try
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.FileName = "cmd";
info.Arguments = "/c \"" + filePath + "\""; //실행 후 cmd.exe를 종료한다.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = info;
proc.Start();
//string result = proc.StandardOutput.ReadToEnd();
//MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
'C#' 카테고리의 다른 글
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
|---|---|
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
| 날짜 문자열을 DateTime형으로 변환 (0) | 2011.10.27 |
| ComboBox SelectedItem (0) | 2011.10.27 |
| QRCode 이미지 제작(zxing 이용) (0) | 2011.08.18 |
날짜 문자열을 DateTime형으로 변환
아래처럼 DateTime.ParseExact를 이용한다.
DateTime date = DateTime.ParseExact("20111027"
, "yyyyMMdd"
, new System.Globalization.CultureInfo("ko-KR"));
또는
DateTime date = DateTime.ParseExact("2011-10-27", "yyyy-MM-dd", null);
null을 입력하여 현재 CultureInfo를 사용한다.
'C#' 카테고리의 다른 글
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
|---|---|
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
| 윈도우에 등록된 확장자를 가진 파일 열기 (0) | 2011.11.16 |
| ComboBox SelectedItem (0) | 2011.10.27 |
| QRCode 이미지 제작(zxing 이용) (0) | 2011.08.18 |
ComboBox SelectedItem
var columnValue = ComboBox.SelectedRow["ColumnName"].ToString(); 또는 var selectedRow = ComboBox.SelectedItem as DataRowView; var columnValue = selectedRow["ColumnName"].ToString();
콤보박스를 선택하고자 할 때
public static DataRowView GetComboSelectedItem(ComboBox cbo
, string columnName, string valueForSelect)
{
foreach (DataRowView row in cbo.Items)
{
if (row[columnName].ToString() == valueForSelect)
{
return row;
}
}
return null;
}
DataTable dt = ...;
cboCombo.DisplayMember = "Text";
cboCombo.ValueMember = "Code";
cboCombo.DataSource = dt;
cboCombo.SelectedItem
= GetComboSelectedItem(cboCombo, "OtherColumnName", "04");
var list = new Dictionary<string, int>();
list.Add("1", 100);
list.Add("2", 200)
list.Add("3", 300);
combobox.DisplayMember="Key";
combobox.ValueMember="Value";
combobox.DataSource = new BindingSource(list, null);
'C#' 카테고리의 다른 글
| 오라클 BLOB 등록 및 조회 (0) | 2016.04.14 |
|---|---|
| 다른 프로젝트의 Resources.resx 파일의 리소스에 접근하기 (0) | 2012.05.07 |
| 윈도우에 등록된 확장자를 가진 파일 열기 (0) | 2011.11.16 |
| 날짜 문자열을 DateTime형으로 변환 (0) | 2011.10.27 |
| QRCode 이미지 제작(zxing 이용) (0) | 2011.08.18 |
