C#에서는 여러가지 방식으로 인코딩 할 수 있도록 Encoding 클래스를 제공해준다.


System.Text 네임스페이스 선언을 해야한다.


Encoding 클래스에 .을 누르면 아래 그림과 같이 여러가지 지원하는 인코딩 방식을 볼 수 있다.



"ABC123 abc!" 문자열을 byte 배열로 인코딩 하는 예제이다.

ASCII(아스키2) 방식의 예제이다. 9번째줄 ASCII 대신에 UTF-8이나 기타 다른 방식에 인코딩 방식을 적어주면 여러 방식에 인코딩으로 변환이 가능하다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Text;
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            Encoding encoding = Encoding.UTF8;
            string str = "ABC123 abc!";
            byte[] encoded = encoding.GetBytes(str);
            foreach(byte b in encoded){
                Console.Write(b+" ");
            }
            Console.WriteLine();
        }
    }
}
 
cs



- 출력 결과 -

65 66 67 49 50 51 32 97 98 99 33

Posted by 꿈만은공돌
,

C#에서 파일 이름, 확장자. 크기, 수정일자 등을 알아낼 수 있습니다.


1. 파일 이름, 확장자 출력

네임스페이스 using System.IO를 포함시켜줍니다. Path 클래스를 사용하면 아래 예제처럼 파일이름을 알 수 있습니다. 이외에도 Path에는 임시폴더를 만들거나 랜덤으로 이름과 확장자를 만들 수도 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.IO;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {            
            string file = @"C:\test\aaa.txt";
            System.Console.WriteLine($"파일이름+확장자 : "
                             + Path.GetFileName(file));
            System.Console.WriteLine($"파일 이름 (확장자없이): " 
                             + Path.GetFileNameWithoutExtension(file));
            System.Console.WriteLine($"확장자 : " 
                             + Path.GetExtension(file));
        }
    }
}
 
cs

- 출력결과 - 

파일이름+확장자 : aaa.txt

파일 이름 (확장자없이): aaa

확장자 : .txt



2. 파일 크기, 접근 일자, 속성 등 출력

위의 예제와 마찬가지로 using System.IO를 포함시켜주어야 합니다.

FileInfo 를 이용해 정보를 얻어올 수 있습니다. 아래 예제와 같이 사용하면 됩니다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.IO;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {            
            string file = @"C:\test\aaa.txt";
            var info = new FileInfo(file);
            System.Console.WriteLine("파일 사이즈: " + info.Length+" Bytes");
            System.Console.WriteLine("생성 시간 : " + info.CreationTime);
            System.Console.WriteLine("수정 시간 : " + info.LastWriteTime);
            System.Console.WriteLine("접근 시간 : " + info.LastAccessTime);
            System.Console.WriteLine("읽기전용 파일 어부 : " + info.IsReadOnly);
            System.Console.WriteLine("디렉터리 이름 : " + info.DirectoryName);
            System.Console.WriteLine("파일 이름 : " + info.Name);
            System.Console.WriteLine("경로+파일 이름 : " + info.FullName);
        }
    }
}
cs


- 출력결과 - 

파일 사이즈: 50 Bytes

생성 시간 : 2018-06-25 오후 8:49:50

수정 시간 : 2018-07-05 오후 9:15:04

접근 시간 : 2018-06-25 오후 8:49:50

읽기전용 파일 어부 : False

디렉터리 이름 : C:\test

파일 이름 : aaa.txt

경로+파일 이름 : C:\test\aaa.txt


아래는 C#에서 파일 및 디렉터리 생성 및 복사 삭제 등에 관한 포스팅 입니다.

2018/07/03 - [닷넷,C#,.NET] - C# 파일 및 디렉터리 생성, 삭제, 복사, 존재여부 검사 등


Posted by 꿈만은공돌
,

C#에서 디렉터리나 파일을 읽고 쓰고 하는등에 클래스에 대해서 알아보자.



1. 디렉터리 존재여부 알기


네임스페이스 using System.IO 를 포함시키고 System.IO.Directory.Exists(string path) 함수를 사용하면 된다.

함수에 이름이 너무 길다면 using static System.IO.Directory; 를 하면 Exists() 만을 사용하면 된다.


아래 예제를 보자. 해당 디렉터리가 있는지 검사하는 예제이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.IO;
using static System.IO.Directory;
 
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {            
            string dir = @"C:\test";
            if (Exists(dir))
            {
                System.Console.WriteLine("해당 폴더 존재");
            }
            else
            {
                System.Console.WriteLine("해당 폴더 없음");
            }
        }
    }
}
cs



2. 디렉터리 만들기, 삭제하기


디렉터리 생성 : System.IO.Directory.CreateDirectory(string path)

삭제 : System.IO.Directory.Delete(string path) 


아래 예제는 해당 디렉터리가 있으면 삭제하고 없으면 생성하는 예제이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.IO;
using static System.IO.Directory;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string dir = @"C:\test";
            if (Exists(dir))
            {
                
                Delete(dir);
                System.Console.WriteLine("폴더 삭제");
            }
            else
            {                
                CreateDirectory(dir);
                System.Console.WriteLine("폴더 만들기");
            }
        }
    }
}
cs



3. 파일 존재여부 검사


디렉터리와 다르게 파일을 다루는 것은 좀더 간단하다. File.Exists(string path) 함수를 사용하면된다.

디렉터리와 마찬가지로 네임스페이스 using System.IO 를 포함시켜준다.


아래 예제는 파일이 존재하는지 검사하는 예제이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.IO;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {
        
            string file = @"C:\test\aaa.txt";
            if (File.Exists(file))
            {
                System.Console.WriteLine("해당 파일 존재");
            }
            else
            { 
                System.Console.WriteLine("해당 파일 없음");
            }
        }
    }
}
cs



4. 파일 생성하기, 텍스트 쓰기, 복사


파일을 생성하는 함수는 File.CreateText(string path) 를 사용하여 만들 수 있다.

원형은 다음과 같다. StreamWriter CreateText(string path);

파일복사는 copy함수를 쓰는데 아래와 같은 원형을 가진다. 마지막 파라미터인 overwrite는 true면 해당 파일이 존재하면 덮어쓰기를 한다.

void Copy(string sourceFileName, string destFileName, bool overwrite);


아래 예제는 파일을 만들어서 텍스트를 쓰고 복사를 한다. StreamWriter 객체로 파일로 생성한 파일을 받아서 WriteLine 로 파일에 내용을 쓴다. 그리고 Dispose 함수로 파일을 닫아준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.IO;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {            
            string textFile = @"C:\test\text.txt";
            string copyFile = @"C:\test\copy.txt";
 
            StreamWriter textWrite = File.CreateText(textFile); //생성
            textWrite.WriteLine("abcdefghijk"); //쓰기
            textWrite.Dispose(); //파일 닫기
 
            File.Copy(textFile, copyFile, true); //복사
        }
    }
}
cs



5. 파일 읽기


StreamReader 클래스를 사용하여 파일을 읽을 수 있다. 객체를 생성하여 File.OpenText(String dir)로 파일을 연다.

읽은 내용을 모두 읽는건 ReadToEnd()를 사용한다.

파일을 닫는건 Dispose()를 사용한다.


아래 예제는 이전 예제에서 복사한 copy.txt 파일을 읽어 화면에 출력한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.IO;
 
namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {            
            string copyFile = @"C:\test\copy.txt";
            StreamReader textReader = File.OpenText(copyFile);
            System.Console.WriteLine(textReader.ReadToEnd());
            textReader.Dispose();
        }
    }
}
 
cs

Posted by 꿈만은공돌
,