'지우기'에 해당되는 글 1건

  1. 2009.02.10 파일 읽고,쓰고,복사,지우기 1
C#2009. 2. 10. 22:18







// 파일 읽기

private void ReadFile()
    {
        textBox1.Text = "";
        string filePath = @"C:\ReadMe3.txt";
        int i = 0;

        using (FileStream fsIn = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            using (StreamReader sr = new StreamReader(fsIn, System.Text.Encoding.Default))
            {
                while (sr.Peek() > -1)      // 조건 peek 는 읽을 데이터가 있으면 읽고 아니면 -1를 반환
                {
                    string input = sr.ReadLine();
                    char[] splitEnter = { '\n' };
                    char[] splitTab = { '\t' };

                    string[] valuesLine = input.Split(splitEnter);      // Line단위로 읽은거
                    string[] valuesTab = valuesLine[0].Split(splitTab); // 탭 단위로 개별 값 읽은거(실제 개별 필드 값)

                    textBox1.Text += valuesLine[0] + "\r\n";
                    i++;
                }
            }
        }
    }

    // 파일 쓰기(텍스트 박스 입력 내용 그래도)

    private void WriteFile()
    {
        string filePath = @"C:\ReadMe2.txt";
        Byte[] info = new UTF8Encoding(true).GetBytes(textBox1.Text);
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); //로컬에 파일 생성
        fs.Write(info, 0, info.Length);
        fs.Close();
    }
     // 파일 카피하고 삭제하기
    private void CopyAndDelelteFile()
    {
        string filePath = @"C:\ReadMe2.txt";
        string newFilePath = @"C:\Temp\ReadMe2.txt";
        File.Copy(filePath, newFilePath);
        File.Delete(filePath);
    }

    // 배열 값을 조합해서 파일 저장(구분은 공백과 줄바꿈)

    private void WriteFile2()
    {
        string filePath = @"C:\ReadMe3.txt";
        string[] aryKey = new string[5] { "1", "2", "3", "4", "5" };
        string[] aryValue = new string[5] { "이명박", "노무현", "김대중", "김영삼", "노태우" };
        string FullText = string.Empty;

        for (int i = 0; i < 5; i++)
        {
            FullText += aryKey[i] + " " + aryValue[i] + "\r\n";
        }
       
        //Byte[] info = new UTF8Encoding(true).GetBytes(FullText);
        Byte[] info = Encoding.GetEncoding("euc-kr").GetBytes(FullText);
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); //로컬에 파일 생성
        fs.Write(info, 0, info.Length);
        fs.Close();
    }

Posted by 댓거리사랑