파일 입출력 예제

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
27
28
29
30
31
32
33
using System;
using System.IO;
 
namespace EX14_FILEIO
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string path = @"D:\Lectures\C#\Examples\EX14_FILEIO\MyTest.txt";
            if (!File.Exists(path))
            {
                // 파일 생성 후 쓰기
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine("My");
                    sw.WriteLine("First");
                    sw.WriteLine("TextFile");
                }
            }
            
            // 파일 읽기
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }
    }
}
cs


바이너리 파일 입출력 예제

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.IO;
 
namespace EX14_FILEIO_BINARY
{
    class MainClass
    {
        private const string FILE_NAME = "highscore.dat";
 
        public static void WriteValues()
        {
            using (BinaryWriter bw = new BinaryWriter(File.Open(FILE_NAME, FileMode.Create)))
            {
                bw.Write("설인범");
                bw.Write(5000);
                bw.Write(10);
                bw.Write(true);
            }
        }
        
        public static void DisplayValues()
        {
            string name;
            int highscore;
            int stage;
            bool item;
            
            if (File.Exists(FILE_NAME ))
            {
                using (BinaryReader br = new BinaryReader(File.Open(FILE_NAME, FileMode.Open)))
                {
                    name = br.ReadString();
                    highscore = br.ReadInt32();
                    stage = br.ReadInt32();
                    item = br.ReadBoolean();
                }
                
                Console.WriteLine("플레이어 : " + name);
                Console.WriteLine("최고점수 : " + highscore);
                Console.WriteLine("스테이지 : " + stage);
                Console.WriteLine("아이템사용 : " + item);
            }
        }
 
        public static void Main (string[] args)
        {
            WriteValues();
            DisplayValues();
        }
    }
}
cs


디렉터리 파일 검색 예제

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
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.IO;
using System.Linq;
 
namespace EX14_FILEIO_DIRECTORY
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            try
            {
                var files = from file in Directory.EnumerateFiles(@"D:\Lectures\C#\Examples\", "*.*", SearchOption.AllDirectories)
                            from line in File.ReadLines(file)
                            where line.Contains("EX")
                            select new {
                                File = file,
                                Line = line
                            };
                
                foreach (var f in files)
                {
                    Console.WriteLine(f.File);
                }
                Console.WriteLine("{0} files found.", files.Count().ToString());
            }
            catch (UnauthorizedAccessException UAEx)
            {
                Console.WriteLine(UAEx.Message);
            }
            catch (PathTooLongException PathEx)
            {
                Console.WriteLine(PathEx.Message);
            }
        }
    }
}
cs


파일 스트림 입출력 예제

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.IO;
using System.Collections.Generic;
 
namespace EX14_FILEIO_STREAM
{
    class Score {
        public string Name { get; set; }
        public int HighScore { get; set; }
    }
 
    class MainClass
    {
        private const string FILE_NAME = @"Score.txt";
        private static List<Score> scores;
 
        private static void InitScoreList() 
        {
            scores = new List<Score> ();
            scores.Add (new Score () { Name = "홍길동", HighScore = 3000 });
            scores.Add (new Score () { Name = "임꺽정", HighScore = 2500 });
            scores.Add (new Score () { Name = "장길산", HighScore = 2000 });
            scores.Add (new Score () { Name = "설인범", HighScore = 1500 });
            scores.Add (new Score () { Name = "도둑넘", HighScore = 1000 });
        }
 
        private static void WriteScore() 
        {
            // StreamWriter를 이용하여 파일 출력
            using (StreamWriter sw = new StreamWriter(FILE_NAME)) {
                foreach(Score s in scores){
                    sw.WriteLine("{0} : {1}", s.Name,s.HighScore);
                }
            }
        }
 
        private static void ReadScore() 
        {
            FileStream fsIn = new FileStream(FILE_NAME,
                                             FileMode.Open,
                                             FileAccess.Read,
                                             FileShare.Read);
            // StreamReader를 이용하여 파일 스트림으로 부터 데이터를 읽는다.
            using (StreamReader sr = new StreamReader(fsIn)) {
                string input;
                while (sr.Peek() > -1) {    // 파일 스트림이 끝날때 까지
                    input = sr.ReadLine();
                    Console.WriteLine(input);
                }
            }
        }
        
        public static void Main (string[] args)
        {        
            InitScoreList();
            WriteScore ();
            ReadScore ();
        }
    }
}
cs


Serialization 예제

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
 
namespace EX14_FILEIO_Serialization
{
    [Serializable]
    public class Score {
        public string Name { get; set; }
        public int HighScore { get; set; }
    }
    
    class MainClass
    {
        private const string FILE_NAME = @"Score.dat";
        private static List<Score> scores;
        
        private static void InitScoreList() 
        {
            scores = new List<Score> ();
            scores.Add (new Score () { Name = "홍길동", HighScore = 3000 });
            scores.Add (new Score () { Name = "임꺽정", HighScore = 2500 });
            scores.Add (new Score () { Name = "장길산", HighScore = 2000 });
            scores.Add (new Score () { Name = "설인범", HighScore = 1500 });
            scores.Add (new Score () { Name = "도둑넘", HighScore = 1000 });
        }
        
        public static void Serialize() 
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
 
            try 
            {
                formatter.Serialize(fs, scores);
            }
            catch (SerializationException e) 
            {
                Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally 
            {
                fs.Close();
            }
        }
        
        public static void Deserialize() 
        {
            scores = null;
            
            // Open the file containing the data that you want to deserialize.
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open);
            try 
            {
                BinaryFormatter formatter = new BinaryFormatter();
                scores = (List<Score>) formatter.Deserialize(fs);
            }
            catch (SerializationException e) 
            {
                Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                throw;
            }
            finally 
            {
                fs.Close();
            }
 
            foreach (Score s in scores) {
                Console.WriteLine("{0} : {1}", s.Name, s.HighScore);
            }
        }
        
        public static void Main (string[] args)
        {        
            InitScoreList();
            Serialize ();
            Deserialize ();
        }
    }
}
cs


+ Recent posts