728x90
300x250

[C#.NET] - MySQL Blob 이미지 읽기, 저장하기

이번에 소개할 것은 C#에서 MySQL Blob를 사용하는 방법에 대해서 소개하려고 합니다.

1. 사용자 인터페이스 구현

그림1) 사용자 인터페이스 설계

c#에서 위의 그림처럼 작성합니다.

2. MySQL - Blob (이미지 저장)

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            string SQL;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;

            string ConString = "Server=hostName;Database=dbName;" +
                               "Uid=userID;Pwd=userPasswd;";

            MySqlConnection con = new MySqlConnection(ConString);
            MySqlCommand cmd = new MySqlCommand();
            BinaryReader br;
            try
            {
                fs = new FileStream(@txtPath.Text, FileMode.Open, FileAccess.Read);
                FileSize = (UInt32)fs.Length;

                rawData = new byte[FileSize];
                fs.Read(rawData, 0, (int)FileSize);
                fs.Close();

                con.Open();

                SQL = "INSERT INTO blob_tbl VALUES(NULL, @FileName, @FileSize, @File)";

                cmd.Connection = con;
                cmd.CommandText = SQL;
                cmd.Parameters.AddWithValue("@FileName", txtPath.Text);
                cmd.Parameters.AddWithValue("@FileSize", FileSize);
                cmd.Parameters.AddWithValue("@File", rawData);

                cmd.ExecuteNonQuery();

                MessageBox.Show("File Inserted into database successfully!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                con.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } // end of try to catch finally

        }
표1) 이미지 저장 소스코드



2. MySQL - Blob (이미지 읽기)

        private void Btn_dbLoad_Click(object sender, EventArgs e)
        {
            string SQL;
            string FileName;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;

            string ConString = "Server=hostName;Database=dbName;" +
                               "Uid=userID;Pwd=userPasswd;";

            MySqlConnection con = new MySqlConnection(ConString);
            MySqlCommand cmd = new MySqlCommand();


            string query = "SELECT * from blob_tbl";

            try
            {
                con.Open();

                cmd.Connection = con;
                cmd.CommandText = query;

                MySqlDataReader myData = cmd.ExecuteReader();

                if (!myData.HasRows)
                    throw new Exception("There are no BLOBs to save");

                myData.Read();

                FileSize = myData.GetUInt32(myData.GetOrdinal("filesize"));
                rawData = new byte[FileSize];

                myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, (int)FileSize);

                FileName = @System.IO.Directory.GetCurrentDirectory() + "\\newfile.png";

                fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(rawData, 0, (int)FileSize);
                fs.Close();

                MessageBox.Show("File successfully written to disk!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                pbBlobImg.Image = Image.FromFile(FileName);

                myData.Close();
                con.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
      }
표2) 이미지 읽기 소스코드

4. 소스코드

Blob.zip
1.57MB



5. 데이터베이스 설계

그림2) 데이터베이스 설계

6. 시연

그림3) 시연하기

 

 

7. 참고자료(Reference)

 

MySQL :: MySQL Connector/NET Developer Guide :: 5.9.2 Writing a File to the Database

5.9.2 Writing a File to the Database To write a file to a database, we need to convert the file to a byte array, then use the byte array as a parameter to an INSERT query. The following code opens a file using a FileStream object, reads it into a byte arra

dev.mysql.com

https://dev.mysql.com/doc/connector-net/en/connector-net-programming-blob-writing.html

 

반응형
728x90
300x250

[C#.NET] A 폼 닫고 B 폼 열기

Visual Basic 6을 사용해보신 분은 'hide'와 'show'만 가지고 자유자재로 컨트롤을 쉽게 제어할 수 있었습니다.
더불어 Application의 닫기 이벤트 또한 내부함수로 구성되어 있어서 사용하기에 편리했습니다.
C#은 문제를 도출하기 위해 다소 다른 방법을 사용합니다.
이 예제는 그러한 상황을 해결하기 위해 만들어졌습니다.


1. 인터페이스 설계

'Sample'이라는 제목을 가지고 있는 A 폼 입니다.
'Main'이라는 제목을 가지고 있는 B 폼 입니다.

 

 

 

 

 

 

 

그림 1) A 폼 닫고 B 폼 열기

솔루션 탐색기에서 'Program.cs'를 클릭합니다.


2. 구현

아래의 글 상자는 초기 소스 코드입니다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace sample
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Login());
        }
    }
}

아래와 같이 신규 선언을 해줍니다.

            Application.Run(new Login());
            Main MainApp = new Main();
            Application.Run(MainApp);


Main은 이 예제의 실제 파일 이름입니다.
Application.Run()은 메인 폼 호출에서 도출해낸 아이디어입니다.



A폼으로 소스(Login.Designer.cs)를 엽니다.
초기 소스는 아래와 같이 선언되어 있음을 알수 있습니다.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sample
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
    }
}


폼을 아래와 같이 구성 합니다.



그리고 버튼을 더블 클릭합니다.

        private void sLogin_Btn_Click(object sender, EventArgs e)
        {
        }


위와 같은 소스가 추가 됨을 알 수가 있습니다.

        {
        }


사이에 소스 코드를 입력합니다.

            Main MainApp = new Main();
            MainApp.Show();

            this.Close();



그리고 B 폼을 신규 윈도우 폼 추가합니다. 폼 이름은 Main으로 설정합니다.

조금 여운을 남겨놓습니다.
Program.cs에 클래스를 활용한다면 A 폼을 종료할 때 B 폼이 강제적으로 실행되는 것을 막을 수 있습니다.

반응형
728x90
300x250

[C#.NET] 동적 컨트롤 제어에 관한 방법

 

 private bool SetCtrlProperty(string CtrlName, string PropName, object value)
 {
        bool result = false;
        Control[] Ctrls = tabPage1.Controls.Find(CtrlName, true);

        if (Ctrls.Length > 0)
        {

              try
             {
              Ctrls[0].GetType().GetProperty(PropName).SetValue(Ctrls[0], value, null);
              result = true;
             }
                catch { }
        }
        return result;
 }

 

사용법

SetCtrlProperty("컨트롤명", "Text", 변경값);

 

참고)

http://blog.naver.com/PostView.nhn?blogId=exila&logNo=80106962981

 

 

반응형
728x90
300x250

[C#.NET] DirectoryInfo - 디렉토리 내 파일 무시하고 강제 삭제

 

디렉토리 내 파일을 무시하고 강제로 삭제하는 방법에 대해서 소개합니다.


1. 구현

 

DirectoryInfo di = new DirectoryInfo(가상의 디렉토리);

di.Delete(부울 조건);

 

부울 조건 : true, false로 처리

 


2. 하위 디렉토리 내 폴더 및 파일 존재 여부 찾기

if(di.GetDirectories().Length != 0 || di.GetFiles().Length != 0)

 

이와 같은 조건으로 찾을 수 있습니다.

 

GetDirectories().Length

(폴더의 수를 의미합니다.)

GetFiles().Length

(파일의 수를 의미합니다.)

 


3. 참고자료(Reference)

 

1. http://msdn.microsoft.com/ko-kr/library/system.io.directoryinfo_methods(v=vs.110).aspx

반응형
728x90
300x250

[C#.NET] AES를 통한 파일 암호화 구현 예제

 

AES를 통한 파일을 암호화하는 방법에 관해 논해보겠습니다.

C#을 통해 파일을 암호화하는 방법입니다.

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

using System.Security; 

using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        // Rfc2898DeriveBytes constants:
        public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

      // Must be at least eight bytes.  MAKE THIS SALTIER!
      public const int iterations = 1042; // Recommendation is >= 1000.


        public static void Main(string[] args)
        {

 

        }

 

복호화(Encrypt)

 

public static void EncryptFile(string inputFile, string outputFile)
{

     try
     {
         string password = @"myKey123"; // Your Key Here
         UnicodeEncoding UE = new UnicodeEncoding();
         byte[] key = UE.GetBytes(password);

         string cryptFile = outputFile;
         FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

         RijndaelManaged RMCrypto = new RijndaelManaged();

         CryptoStream cs = new CryptoStream(fsCrypt,
         RMCrypto.CreateEncryptor(key, key),
         CryptoStreamMode.Write);

         FileStream fsIn = new FileStream(inputFile, FileMode.Open);

         int data;
         while ((data = fsIn.ReadByte()) != -1)
              cs.WriteByte((byte)data);


              fsIn.Close();
              cs.Close();
              fsCrypt.Close();
        }
     catch
     {

     }
}

 

부호화(Decrypt)

 

/// Decrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
public static void DecryptFile(string inputFile, string outputFile)
{

    {
        string password = @"myKey123"; // Your Key Here

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

        RijndaelManaged RMCrypto = new RijndaelManaged();

        CryptoStream cs = new CryptoStream(fsCrypt,
        RMCrypto.CreateDecryptor(key, key),
        CryptoStreamMode.Read);

        FileStream fsOut = new FileStream(outputFile, FileMode.Create);

    

        int data;
        while ((data = cs.ReadByte()) != -1)
             fsOut.WriteByte((byte)data);

             fsOut.Close();
             cs.Close();
             fsCrypt.Close();

        }
}

반응형
728x90
300x250

[ExcelObj].NET 개발자의 관점에서 파악한 Excel 개체 모델 - VS2012기준

 

(Office 2010 이상, Visual Studio 2012 기준)

 

http://msdn.microsoft.com/ko-kr/library/bb386107.aspx

(한국)

 

참고하시면 좋은 자료가 될거 같습니다.

반응형
728x90
300x250

[ExcelObj].NET 개발자의 관점에서 파악한 Excel 개체 모델

 

http://www.microsoft.com/en-us/download/confirmation.aspx?id=4640 

(영문)

 

http://msdn.microsoft.com/ko-kr/library/aa168292(OFFICE.11).aspx

(한국)

 

닷넷 기반의 엑셀 제어 기술에 대한 예제입니다.

마이크로소프트에서 공식제공합니다.

 

 

ExcelObj.exe

 

반응형
728x90
300x250
[C#] 하드웨어 정보 가져오기 - 구현 방법

 

C#으로 하드웨어 정보 가져오기에 대한 구현 방법을 소개하고자 합니다.

 


1. 참조 라이브러리


솔루션 -> 참조 -> Microsoft.VisualBasic

 


2. 구현


using System.Management;

 

private void Form2_Load(object sender, EventArgs e)
{
            int i;

            /// 배치 장소
            c_area.Items.Add("본사");
            c_area.Items.Add("영업지사");
            c_area.Items.Add("개발");


            /// 배치 부서
            c_department.Items.Add("사무실");
            c_department.Items.Add("생산");
            c_department.Items.Add("설계");
            c_department.Items.Add("출하");
            c_department.Items.Add("회의실");
            c_department.Items.Add("사장실");


            /// 자산 구분
            c_asset.Items.Add("소유");
            c_asset.Items.Add("임대");


            /// 자산 형태
            c_type.Items.Add("데스크탑");
            c_type.Items.Add("노트북");
            c_type.Items.Add("넷북");
            c_type.Items.Add("타블렛노트");
           
            // 전산장비 정보 가져오기

            // 1. CPU 정보 가져오기
            ManagementObjectSearcher MS2 = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_CPU.Text = MO["Name"].ToString();
            }
            // 2. RAM 정보 가져오기
            ulong a = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024;
            string b = a.ToString() + "MB";
            c_RAM.Text = b;
            // 3. M/B 정보 가져오기
            MS2 = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_MB.Text = MO["Product"].ToString();
            }
            // 4. VGA 정보 가져오기
            MS2 = new ManagementObjectSearcher("Select * from Win32_DisplayConfiguration");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_VGA.Text = MO["Description"].ToString();
            }
            // 5. HDD 정보 가져오기

            List<HardDrive> hdCollection = new List<HardDrive>();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

            foreach (ManagementObject wmi_HD in searcher.Get())
            { 
               HardDrive hd = new HardDrive();
               hd.Model = wmi_HD["Model"].ToString();
               hd.Type = wmi_HD["InterfaceType"].ToString();
               hdCollection.Add(hd);
            }
            searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
            int ii = 0;
            foreach (ManagementObject wmi_HD in searcher.Get())
            {
                if (ii >= hdCollection.Count)
                {
                    break;
                }
           
                HardDrive hd = (HardDrive)hdCollection[ii];
                // get the hardware serial no.

                if (wmi_HD["SerialNumber"] == null)
                    hd.SerialNo = "None";
                else
                    hd.SerialNo = wmi_HD["SerialNumber"].ToString().Trim();

                ++ii;
            }

            c_HDD_1.Text = hdCollection[0].Model.ToString();
            c_HDD_Type_1.Text = hdCollection[0].Type.ToString();
            if (hdCollection.Count < 1)
            {
                c_HDD_2.Text = hdCollection[1].Model.ToString();
                c_HDD_Type_2.Text = hdCollection[1].Type.ToString();
            }
        }

       

 

// 하드 정보담는 공간
        public class HardDrive
        {
            private string model = null;
            private string type = null;
            private string serialNo = null;
            public string Model
            {
                get { return model; }
                set { model = value; }
            }
            public string Type
            {
                get { return type; }
                set { type = value; }
            }
            public string SerialNo
            {
                get { return serialNo; }
                set { serialNo = value; }
            }
        }

 

 


3. 참고자료(Reference)


1. http://anothermsdn.com/?paged=13, Accessed by 2013-08-04

=> 현재 웹사이트 폐쇠됨.

 

반응형

+ Recent posts