728x90

C# 독학하는 초보자인데 질문하신 분이 있어서 올립니다.

Encoding 자동 감지하는 소스를 올리지 않습니다.

그 부분은 Encoding enc = Encoding.Default;

와 같이 코드를 수동으로 처리해서 테스트하시기 바랍니다.


using System.IO;
private void btnHangul_Click(object sender, EventArgs e)
{
    // 한글이 포함되어 있는지 검사
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Filter = "csv (*.csv) | *.csv";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            Read_CSV_firstColumn(dlg.FileName);
        }
    }
}

public void Read_CSV_firstColumn(string fileName)
{
    string delimiter = ";";  // 구분자
    Encoding enc = GetFileEncoding(fileName);
    if (enc == null)
    {
        MessageBox.Show("Encoding Detection failed.");
        return;
    }

    using (var sr = new StreamReader(fileName, enc, true))
    {
        string line = null;
        while ((line = sr.ReadLine()) != null)
        {
            string[] fields = line.Split(new string[] { delimiter }, StringSplitOptions.None);
            if (isContainHangul(fields[0]))  // 첫번째 칼럼에 한글이 포함되어 있으면
            {
                MessageBox.Show(fields[0] + " : 한글 포함되어 있네요");
            }
            else
            {
                MessageBox.Show(fields[0] + " : 한글 포함 안되어 있어요");
            }
        }
        sr.Close();
    }
}

/// <summary>
/// 문자열에 한글이 포함되어 있는지 검사하여 포함되어 있으면 true 반환
/// </summary>
public bool isContainHangul(string s)
{
    char[] charArr = s.ToCharArray();
    foreach (char c in charArr)
    {
        if (char.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.OtherLetter)
        {
            return true;
        }
    }
    return false;
}


블로그 이미지

Link2Me

,