[텍스트 파일 쓰기]

StreamWriter writer;
writer = File.CreateText(Environment.CurrentDirectory + "\\" + FileName + ".txt");

       for(int = 0; i<10; i++) 
       {
            writer.WriteLine(i.ToString());
       }
       
writer.Close();

 

[텍스트 파일 읽기]

StreamReader file = new StreamReader(path);
try
{
        while ((line = file.ReadLine()) != null)
		{
               Console.WriteLine(line);
        }
 }
catch (Exception ex) 
{
        // Error.
}

비쥬얼 스튜디오의 C#에서 카카오 i API를 사용하기 위해서는 일단 제일먼저

 

API키를 발급 받아야 한다.

 

[ref link]

developers.kakao.com/docs/latest/ko/translate/common

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

키를 발급받았다면, 아래 코드를 입력해준다.

 

[Program.cs]

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Kakao_Trans
{
    class Program
    {
        static void Main(string[] args)
        {
            Kakao_Trans();
        }

        private static void Kakao_Trans() 
        {
            try
            {
                string type = "src_lang=en&target_lang=kr"; // 요청하고자 하는 번역 타입
                string site = "https://kapi.kakao.com/v1/translation/translate?" + type + "&query=";
                string Original_string = "Where are you from?"; // 번역하고 싶은 원본 데이터

                string query = string.Format("{0}{1}", site, Original_string); // 최종적으로 요청하는 번역 쿼리

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);

                string rkey = "API KEY 입력"; // API 키

                string header = "KakaoAK " + rkey;

                request.Headers.Add("Authorization", header);
                request.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string status = response.StatusCode.ToString();

                if (status == "OK")
                {
                    Stream stream = response.GetResponseStream();

                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);

                    String text = reader.ReadToEnd();

                    stream.Close();
                    response.Close();
                    reader.Close();

                    int start = text.IndexOf("[\"") + 2;
                    int end = text.IndexOf("\"]", start);

                    Console.WriteLine(text.Substring(start, end - start));
                }
                else
                {
                    // 오류발생
                }
            }
            catch (Exception ex)
            {
                //api에서 문제가 생겨도 여기서 오류가 발생한다.
                //오류 내용을 확인해서 로그를 남겨야 할듯
            }
        }
    }
}

 

참고로!

string rkey = "API KEY 입력"; // API 키

이 코드 부분에 발급받았던 키를 입력해 줘야된다.

 

 

[실행 결과]

비쥬얼 스튜디오의 C#에서 파파고 API를 사용하기 위해서는 일단 제일먼저

 

API키를 발급 받아야 한다.

 

[ref link]

developers.naver.com/products/nmt/

 

Papago 소개

Neural Machine Translation NMT는 Neural Machine Translation(인공신경망 기반 기계번역)의 약어입니다. 파파고의 NMT 기술은 입력 문장을 문장벡터로 변환하는 신경망(encoder)과 문장벡터에서 번역하는 언어의 �

developers.naver.com

 

위에서 발급 받으면 된다.

 

그리면 Client ID 와, Client Secret 코드를 발급받게 된다.

 

 

[Program.cs]

using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Papago_Trans
{
    class Program
    {
        static void Main(string[] args)
        {
            Papago_Trans();
        }

        private static void Papago_Trans() 
        {
            try
            {
                // 요청 url
                string sUrl = "https://openapi.naver.com/v1/papago/n2mt";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
                // 헤더 추가하기 (파파고 NMT API 가이드에서 -h 부분이 헤더이다)
                request.Headers.Add("X-Naver-Client-Id", "API 아이디 코드");
                request.Headers.Add("X-Naver-Client-Secret", "API 시크릿 코드");
                request.Method = "POST";

                // 파라미터에 값 넣기 (파파고 NMT API가이드에서 -d부분이 파라미터)
                //string sParam = string.Format("source=auto&target=en&text="+txtSendText.Text);

                string Original_string = "Where are you from?"; // 번역하고싶은 데이터

                // 파라미터를 char Set에 맞게 변경
                byte[] bytearry = Encoding.UTF8.GetBytes("source=en&target=ko&text=" + Original_string);

                request.ContentType = "application/x-www-form-urlencoded";

                // 요청 데이터 길이
                request.ContentLength = bytearry.Length;

                Stream st = request.GetRequestStream();
                st.Write(bytearry, 0, bytearry.Length);
                st.Close();

                // 응답 데이터 가져오기 (출력포맷)
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string text = reader.ReadToEnd();

                stream.Close();
                response.Close();
                reader.Close();

                JObject jObject = JObject.Parse(text);
                Console.WriteLine(jObject["message"]["result"]["translatedText"].ToString()); // 결과 출력
            }
            catch (Exception ex)
            {
                //api에서 문제가 생겨도 여기서 오류가 발생한다.
                //오류 내용을 확인해서 로그를 남겨야 할듯
            }
        }
    }
}

 

[참고]

                // 헤더 추가하기 (파파고 NMT API 가이드에서 -h 부분이 헤더이다)
                request.Headers.Add("X-Naver-Client-Id", "API 아이디 코드");
                request.Headers.Add("X-Naver-Client-Secret", "API 시크릿 코드");

여기 부분에 있는 API 아이디 코드와, 시크릿 코드는 본인이 발급받은 내용을 적어주면

정상적으로 작동할 것이다!

 

 

[실행 결과]

구글 번역기 API를 사용하기 위해서는 해당 API 키를 먼저 발급받아야 한다.

 

[ref link]

console.developers.google.com/

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

 

키를 발급받았다면, 비쥬얼스튜디오에서 필요한 NuGet을 설치한다.

 

솔루션용 NuGet 패키지 설치

 

그리고 나서 솔루션 창이 나오면

 

Google.Apis.Translate.v2

Google.Apis.Translate.v2 를 설치해준다.

 

마지막으로

 

해당 코드를 입력한다.

 

[Program.cs]

using Google.Apis.Services;
using Google.Apis.Translate.v2;
using Google.Apis.Translate.v2.Data;
using System;

namespace Google_Trans
{
    class Program
    {
        static void Main(string[] args)
        {
            Google_Trans();
        }

        private static void Google_Trans() 
        {
            TranslateService service = new TranslateService(new BaseClientService.Initializer()
            {
                ApiKey = "API KEY 입력", // 여기만 바꾸면 됨.
                ApplicationName = " "
            });

            string Original_string = "Where are you from?"; // 해당 글 번역 요청
            try
            {
                try
                {
                    //번역 요청
                    TranslationsListResponse response = service.Translations.List(Original_string, "ko").Execute();
                    //번역 결과
                    Console.WriteLine(response.Translations[0].TranslatedText);
                }
                catch (Exception ex)
                {
                    //api에서 문제가 생겨도 여기서 오류가 발생한다.
                    //오류 내용을 확인해서 로그를 남겨야 할듯
                }
            }
            catch (Exception ex)
            {
                //오류 내용을 확인해서 로그를 남겨야 할듯
            }
        }
    }
}

 

참고로 마지막에 

TranslationsListResponse response = service.Translations.List(Original_string, "ko").Execute();

여기서 Original_string 은 타입에 따라 자동으로 언어가 지정된다.

 

 

[실행 결과]

보통 프로그램을 만들기 위해서는 visual studio 같은 개발 툴이 필요하다.

 

하지만, 별도의 툴 없이 간단한 코드를 테스트하고 결과를 확인할 수 있는 사이트가 있다.

 

[ref link]

repl.it/

 

The collaborative browser based IDE

Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin, QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript,

repl.it

 

구글 계정이나, 깃허브 계정만 있으면 손 쉽게 할 수 있다!

 

실행결과

 

짠 이런식으로 :)

주로 MSsql을 이용해서 작업을 했는데,

 

SQLite를 이용하여 작업을 하게되는 일이 생겼다.

 

그래서 자주 사용하는 쿼리를 메모한다.

 

SELECT

SELECT * FROM Table;
SELECT * FROM Table LIMIT 10; // mssql로 치면 Top 같은건데 다른점은 sqlite같은 경우는 뒤에서 지정해줘야한다.

 

INSERT

INSERT INTO Table VALUES (Int, 'str1', 'str2'); // 특별히 변수를 지정해주고 싶으면 Table뒤에 (변수1, 변수2...) 이렇게

 

UPDATE

UPDATE Table SET colum1 = 'str1', colum2 = 'str2' WHERE key=value;

 

DELETE

DELETE FROM Table WHERE key=value;

mssql 쿼리를 처리하다보면

 

"&근처의 구문이 잘못되었습니다." 라는 오류를 흔히 볼 수 있다.

 

보통 sql server에서는 문자열 처리할 때 작은 따옴표를 사용하는데,

 

이럴때는 ' 이 부분 앞에 '' 이렇게 작은따옴표를 2개 붙여주면된다.

 

 

예를 들어, C# 기준으로 설명을 하자면

 

C#에서는 문자열을 바꿔주는 기능이 있다. String.Replace !!

 

 

따라서

 

string.Replace("'", "''");

 

이렇게하면 데이터를 유지하고 넣을 수 있다.

C#의 윈폼으로 데이터를 다룰 때, 그리드 뷰를 많이 사용한다.

근데 그 데이터가 많이 있을 때 더 편리하게 보기 위해서 페이징 기능이 있으면 좋겠다.

 

Data Grid View

DB는 SQLite를 사용했으며,

코드는 아래와 같다.

 

Form1.Designer.cs

namespace GridView_Paging
{
    partial class Form1
    {
        /// <summary>
        /// 필수 디자이너 변수입니다.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// 사용 중인 모든 리소스를 정리합니다.
        /// </summary>
        /// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows Form 디자이너에서 생성한 코드
        /// <summary>
        /// 디자이너 지원에 필요한 메서드입니다. 
        /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
        /// </summary>
        private void InitializeComponent()
        {
            this.logGridView1 = new System.Windows.Forms.DataGridView();
            this.label1 = new System.Windows.Forms.Label();
            this.btnPre = new System.Windows.Forms.Button();
            this.btnNext = new System.Windows.Forms.Button();
            this.btn조회 = new System.Windows.Forms.Button();
            this.btnFirst = new System.Windows.Forms.Button();
            this.btnLast = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.txtPageSize = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.logGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // logGridView1
            // 
            this.logGridView1.AllowUserToAddRows = false;
            this.logGridView1.AllowUserToDeleteRows = false;
            this.logGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.logGridView1.Location = new System.Drawing.Point(10, 10);
            this.logGridView1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.logGridView1.Name = "logGridView1";
            this.logGridView1.ReadOnly = true;
            this.logGridView1.RowTemplate.Height = 27;
            this.logGridView1.Size = new System.Drawing.Size(667, 370);
            this.logGridView1.TabIndex = 0;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(296, 401);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(44, 12);
            this.label1.TabIndex = 1;
            this.label1.Text = "Page /";
            // 
            // btnPre
            // 
            this.btnPre.FlatAppearance.BorderSize = 0;
            this.btnPre.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnPre.Location = new System.Drawing.Point(246, 394);
            this.btnPre.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.btnPre.Name = "btnPre";
            this.btnPre.Size = new System.Drawing.Size(38, 26);
            this.btnPre.TabIndex = 2;
            this.btnPre.Text = "<";
            this.btnPre.UseVisualStyleBackColor = true;
            this.btnPre.Click += new System.EventHandler(this.btnPre_Click);
            // 
            // btnNext
            // 
            this.btnNext.FlatAppearance.BorderSize = 0;
            this.btnNext.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnNext.Location = new System.Drawing.Point(375, 394);
            this.btnNext.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.btnNext.Name = "btnNext";
            this.btnNext.Size = new System.Drawing.Size(38, 26);
            this.btnNext.TabIndex = 4;
            this.btnNext.Text = ">";
            this.btnNext.UseVisualStyleBackColor = true;
            this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
            // 
            // btn조회
            // 
            this.btn조회.Location = new System.Drawing.Point(10, 394);
            this.btn조회.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.btn조회.Name = "btn조회";
            this.btn조회.Size = new System.Drawing.Size(88, 24);
            this.btn조회.TabIndex = 5;
            this.btn조회.Text = "조회";
            this.btn조회.UseVisualStyleBackColor = true;
            this.btn조회.Click += new System.EventHandler(this.btn조회_Click);
            // 
            // btnFirst
            // 
            this.btnFirst.FlatAppearance.BorderSize = 0;
            this.btnFirst.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnFirst.Location = new System.Drawing.Point(203, 394);
            this.btnFirst.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.btnFirst.Name = "btnFirst";
            this.btnFirst.Size = new System.Drawing.Size(38, 26);
            this.btnFirst.TabIndex = 7;
            this.btnFirst.Text = "<<";
            this.btnFirst.UseVisualStyleBackColor = true;
            this.btnFirst.Click += new System.EventHandler(this.btnFirst_Click);
            // 
            // btnLast
            // 
            this.btnLast.FlatAppearance.BorderSize = 0;
            this.btnLast.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnLast.Location = new System.Drawing.Point(419, 394);
            this.btnLast.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.btnLast.Name = "btnLast";
            this.btnLast.Size = new System.Drawing.Size(38, 26);
            this.btnLast.TabIndex = 8;
            this.btnLast.Text = ">>";
            this.btnLast.UseVisualStyleBackColor = true;
            this.btnLast.Click += new System.EventHandler(this.btnLast_Click);
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(541, 400);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(36, 12);
            this.label2.TabIndex = 9;
            this.label2.Text = "ROW:";
            // 
            // txtPageSize
            // 
            this.txtPageSize.Location = new System.Drawing.Point(588, 396);
            this.txtPageSize.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.txtPageSize.Name = "txtPageSize";
            this.txtPageSize.Size = new System.Drawing.Size(88, 21);
            this.txtPageSize.TabIndex = 10;
            this.txtPageSize.Text = "100";
            this.txtPageSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(688, 428);
            this.Controls.Add(this.txtPageSize);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.btnLast);
            this.Controls.Add(this.btnFirst);
            this.Controls.Add(this.btn조회);
            this.Controls.Add(this.btnNext);
            this.Controls.Add(this.btnPre);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.logGridView1);
            this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.logGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion
        private System.Windows.Forms.DataGridView logGridView1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnPre;
        private System.Windows.Forms.Button btnNext;
        private System.Windows.Forms.Button btn조회;
        private System.Windows.Forms.Button btnFirst;
        private System.Windows.Forms.Button btnLast;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtPageSize;
    }
}

 

 

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GridView_Paging
{
    public partial class Form1 : Form
    {
        int PageCount;
        int maxRec;
        int pageSize;
        int currentPage;
        int recNo;
        DataSet ds;
        DataTable table = new DataTable();
        SQLiteDataAdapter log_adapter;
        public Form1()
        {
            InitializeComponent();
        }
        private void btn조회_Click(object sender, EventArgs e)
        {
            string connStr = @"UserPath\_.db"; // --- 임시용
            try
            {
                using (var conn = new SQLiteConnection(connStr))
                {
                    conn.Open();
                    string sql = "SELECT * FROM Table";
                    log_adapter = new SQLiteDataAdapter(sql, conn);
                    ds = new DataSet();
                    log_adapter.Fill(ds, "EventLogs");
                    table = ds.Tables["EventLogs"];
                    // Set the start and max records. 
                    pageSize = Convert.ToInt32(txtPageSize.Text);
                    maxRec = table.Rows.Count;
                    PageCount = maxRec / pageSize;
                    //Adjust the page number if the last page contains a partial page.
                    if ((maxRec % pageSize) > 0)
                    {
                        PageCount += 1;
                    }
                    // Initial seeings
                    currentPage = 1;
                    recNo = 0;
                    // Display the content of the current page.
                }
            }
            catch (Exception ex)
            {
                // 오류
            }
            
            LoadPage();
        }
        private void LoadPage()
        {
            int i;
            int startRec;
            int endRec;
            DataTable dtTemp;
            //Clone the source table to create a temporary table.
            dtTemp = table.Clone();
            if (currentPage == PageCount)
            {
                endRec = maxRec;
            }
            else
            {
                endRec = pageSize * currentPage;
            }
            startRec = recNo;
            //Copy rows from the source table to fill the temporary table.
            for (i = startRec; i < endRec; i++)
            {
                dtTemp.ImportRow(table.Rows[i]);
                recNo += 1;
            }
            logGridView1.DataSource = dtTemp;
            DisplayPageInfo();
        }
        private void DisplayPageInfo()
        {
            label1.Text = "Page " + currentPage.ToString() + "/ " + PageCount.ToString();
        }
        private bool CheckFillButton()
        {
            // Check if the user clicks the "Fill Grid" button.
            if (pageSize == 0)
            {
                MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
                return false;
            }
            else
            {
                return true;
            }
        }
        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (CheckFillButton() == false)
            {
                return;
            }
            //Check if you are already at the first page.
            if (currentPage == 1)
            {
                MessageBox.Show("You are at the First Page!");
                return;
            }
            currentPage = 1;
            recNo = 0;
            LoadPage();
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            //If the user did not click the "Fill Grid" button, then return.
            if (CheckFillButton() == false)
            {
                return;
            }
            //Check if the user clicks the "Fill Grid" button.
            if (pageSize == 0)
            {
                MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
                return;
            }
            currentPage += 1;
            if (currentPage > PageCount)
            {
                currentPage = PageCount;
                //Check if you are already at the last page.
                if (recNo == maxRec)
                {
                    MessageBox.Show("You are at the Last Page!");
                    return;
                }
            }
            LoadPage();
        }
        private void btnPre_Click(object sender, EventArgs e)
        {
            if (CheckFillButton() == false)
            {
                return;
            }
            if (currentPage == PageCount)
            {
                recNo = pageSize * (currentPage - 2);
            }
            currentPage -= 1;
            //Check if you are already at the first page.
            if (currentPage < 1)
            {
                MessageBox.Show("You are at the First Page!");
                currentPage = 1;
                return;
            }
            else
            {
                recNo = pageSize * (currentPage - 1);
            }
            LoadPage();
        }
        private void btnLast_Click(object sender, EventArgs e)
        {
            if (CheckFillButton() == false)
            {
                return;
            }
            //Check if you are already at the last page.
            if (recNo == maxRec)
            {
                MessageBox.Show("You are at the Last Page!");
                return;
            }
            currentPage = PageCount;
            recNo = pageSize * (currentPage - 1);
            LoadPage();
        }  
    }
}

+ Recent posts