본문 바로가기
프로그래밍/Unity 코드

C# xml, json, txt, binary 타입 읽고 쓰기

by 눈야옹 2016. 2. 5.
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
using System.Reflection;
using System.Net.Json;
 
namespace FileSaveLoad
{
    public enum E_FileType
    {
        E_FileType_None,
        E_FileType_txt,
        E_FileType_xml,
        E_FileType_json,
        E_FileType_binary,
        E_FileType_etc
    }
 
    struct stTest
    {
        public string name;
        public int age;
        public int sex;
        public string message;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            cFileLoadSave pFS = new cFileLoadSave();
            pFS.Update();
        }
    }
 
    class cFileLoadSave
    {
        private string FilePath = "";
        public string FileName = "";
 
        public E_FileType eFileType;
 
        stTest user1;
        stTest user2;
        stTest user3;
        List<stTest> list_UserData = new List<stTest>();
 
        List<stTest> list_UserCopyData = new List<stTest>();
 
        public void Update()
        {
            eFileType = E_FileType.E_FileType_txt;
 
            string s = Console.ReadLine();
            int n = System.Convert.ToInt16(s);
 
            eFileType = (E_FileType)n;
 
            switch (eFileType)
            {
                case E_FileType.E_FileType_txt:
                    FilePath = "txtTest.txt";
                    break;
                case E_FileType.E_FileType_xml:
                    FilePath = "xmlTest.xml";
                    break;
                case E_FileType.E_FileType_json:
                    FilePath = "jsonTest.json";
                    break;
                case E_FileType.E_FileType_binary:
                    FilePath = "binTest.bin";
                    break;
                default:
                    Console.WriteLine("No Function");
                    break;
            }
 
            DataCreate();
            Save(FilePath);
            Load(FilePath);
            PrintCopyData();
        }
 
        void PrintCopyData()
        {
            for (int i = 0; i < list_UserCopyData.Count; ++i)
            {
                Console.WriteLine(list_UserCopyData[i].name);
                Console.WriteLine(list_UserCopyData[i].age);
                Console.WriteLine(list_UserCopyData[i].sex);
                Console.WriteLine(list_UserCopyData[i].message);
            }
        }
 
        void BinaryFileSave(string _fullPath, List<stTest> _SaveData)
        {
            FileStream fs = new FileStream(_fullPath, FileMode.Create);
 
            // 단일 바이트 쓰기
            // fs.WriteByte(0x01);
            // fs.WriteByte(0x99);
            // fs.WriteByte(0x55);
            // fs.WriteByte(0xFF);
 
            Byte[] asciiByte = Encoding.ASCII.GetBytes("ASCII string data");
            Byte[] uniByte = Encoding.Unicode.GetBytes("유니코드 문자열");
            //ASCII 쓰기
            fs.Write(asciiByte, 0, asciiByte.Length);
            //줄바꿈 \r \n
            fs.WriteByte(13);
            fs.WriteByte(10);
            // UNICODE  쓰기
            fs.Write(uniByte, 0, uniByte.Length);
 
            Byte[] dummyAsciiByte = new Byte[asciiByte.Length];
            Byte[] dummyUniByte = new Byte[uniByte.Length];
 
 
            fs.Read(dummyAsciiByte, 0, dummyAsciiByte.Length);
            Console.WriteLine("읽은 ASCII 바이트: {0}"Encoding.ASCII.GetString(dummyAsciiByte));
 
            // 줄바꿈 문자(\r\n)를 읽어주고
            fs.ReadByte();
            fs.ReadByte();
 
            // 쓴 UNICODE 바이트를 읽고 출력해보자!
            fs.Read(dummyUniByte, 0, dummyUniByte.Length);
            Console.WriteLine("읽은 UNICODE 바이트: {0}"Encoding.Unicode.GetString(dummyUniByte));
 
            fs.Close();
 
        }
 
        void BinaryFileLoad(string _fullPath, out List<stTest> _LoadData)
        {
            _LoadData = new List<stTest>();
        }
 
        void JsonFileLoad(string _fullPath, out List<stTest> _LoadData)
        {
            _LoadData = new List<stTest>();
 
        }
 
        void JsonFileSave(string _fullPath, List<stTest> _SaveData)
        {
            JsonObjectCollection JsonObjCol = new JsonObjectCollection();
            JsonTextParser jt = new JsonTextParser();
 
 
            JsonObjCol.Name = "User";
 
            JsonObjCol.Add(new JsonStringValue("id""kim"));
            JsonObjCol.Add(new JsonBooleanValue("sex"true));
            JsonObjCol.Add(new JsonNumericValue("age"100));
 
            string strJson = JsonObjCol.ToString();
            Console.WriteLine("col1 : {0}", strJson);
            //=====
            JsonObjectCollection JsonObjCol2 = new JsonObjectCollection();
 
            JsonObjCol2.Add(JsonObjCol);
            JsonObjCol2.Add(JsonObjCol["age"]);
            JsonObjCol2.Add(new JsonStringValue("message""hohohoho"));
 
            string strJson2 = JsonObjCol2.ToString();
            Console.WriteLine("col2 : {0}", strJson2);
            //==========
            JsonTextParser jsonText = new JsonTextParser();
            JsonObject jsonObj = jsonText.Parse(strJson2);
            string strObj = jsonObj.ToString(); // only name
            Console.WriteLine("obj : {0}", strObj);
 
            JsonObjectCollection col3 = (JsonObjectCollection)jsonObj;
            string strJson3 = col3.ToString();
            Console.WriteLine("col3 : {0}", strJson3);
 
            string comm = Convert.ToString(col3["message"].GetValue());
            Console.WriteLine("message : {0}", comm);
        }
 
 
        void XmlFileLoad(string _fullPath, out List<stTest> _LoadData)
        {
            _LoadData = new List<stTest>();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_fullPath);
            XmlNode Root = xmlDoc.DocumentElement;
            XmlNodeList allUserNodes = Root.ChildNodes;
 
            for (int i = 0; i < allUserNodes.Count; ++i)
            {
                var temp = new stTest();
                var Fields = temp.GetType().GetFields();
                for (int m = 0; m < allUserNodes[i].ChildNodes.Count; ++m)
                {
                    string fieldname = allUserNodes[i].ChildNodes[m].Name;
                    var field = temp.GetType().GetField(fieldname);
                    object box = temp;
                    var data = allUserNodes[i].ChildNodes[m].InnerText;
                    string str = "";
                    if (temp.GetType().GetField(fieldname).FieldType == typeof(string))
                    {
                        field.SetValue(box, data);
                    }
                    else
                    {
                        int num = Convert.ToInt16(data);
                        field.SetValue(box, num);
                    }
 
                    temp = (stTest)box;
 
                }
                _LoadData.Add(temp);
            }
 
        }
 
        void XmlFileSave(string _fullPath, List<stTest> _SaveData)
        {
            //파일 인포를 받아와서 
            FileInfo fileInfo = new FileInfo(_fullPath);
 
            // 문서를 만들고 지정된 값의 노드를 만든다.
            XmlDocument XmlDoc = new XmlDocument();
 
            //해당 이름을 가진 파일이 있나 찾아본다.
            if (fileInfo.Exists)
            {
                //만약 있다면 로딩
                XmlDoc.Load(_fullPath);
            }
            else
            {
                //만약 없다면 새로 만든다
 
                XmlDoc.AppendChild(XmlDoc.CreateXmlDeclaration("1.0""utf-8""yes"));
                // 최상위 노드(Root)를 만든다.
                XmlNode newRootNode = XmlDoc.CreateElement("""Root""");
                XmlDoc.AppendChild(newRootNode);
            }
            //만든 혹은 만들어져 있던 Root노드를 받아온다.
            XmlNode rootNode = XmlDoc.DocumentElement;
 
            //**구조체의 필드 변수들  이름을 가져오기
            //** 구조체 타입을 받아온다.
            Type type = typeof(stTest);
            //** 구조체의 퍼블릭,넌 퍼블릭 , 인스턴스를 필드 인포 배열로 받아온다.
            //그럼 배열로 각각의 배열안에 있는 변수형과 변수명을 알수있다.
            System.Reflection.FieldInfo[] fieldInfo = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            //
 
            for (int i = 0; i < _SaveData.Count; ++i)
            {
                string ElementName = "User" + (i + 1);
                XmlNode node = FindNode(rootNode, XmlDoc, ElementName);
 
                if (node.ChildNodes.Count > 0)
                {
                    node.RemoveAll();
                }
                //만약 데이터가 없다면 생성
                for (int f = 0; f < fieldInfo.Length; ++f)
                {
                    node.AppendChild(
                        CreateXmlNode(XmlDoc,
                                               //** 아까 받아온 변수명을 넣어주고
                                               fieldInfo[f].Name,
                                               //** 구조체. 타입으로 접근. 타입이 가지고 있는 필드중 . 위에 넣은 필드명(변수명)과 같은 것이 가지고 있는 값을(i번재 구조체에서 ) 가져와 넣는다.
                                               _SaveData[i].GetType().GetField(fieldInfo[f].Name).GetValue(_SaveData[i]).ToString()
                        ));
                }
            }
            // 지정된 XML문서로 만들고 저장한다.
            // xml에서 화살표 닫고 열수잇는 돌더 명들이 있는데 이것이 element이고 이안에 이름과 값을 같이 가지고 있는것들이 노드이다.
            // 물론 element도 노드와 같이 ele이름 이외에 이름과 값을 또 저장할수 있다. 
            XmlDoc.Save(_fullPath);
        }
 
        XmlNode FindNode(XmlNode _root, XmlDocument _Doc, string _eleName)
        {
            for (int i = 0; i < _root.ChildNodes.Count; ++i)
            {
                if (_root.ChildNodes.Item(i).Name == _eleName)
                {
                    return _root.ChildNodes.Item(i);
                }
            }
            //검색해서 없다면
            XmlElement NewEle = _Doc.CreateElement(_eleName);
            return _root.AppendChild(NewEle);
        }
 
        XmlNode CreateXmlNode(XmlDocument _xmlDoc, string _name, string _data)
        {
            XmlNode node = _xmlDoc.CreateElement(string.Empty, _name, string.Empty);
            node.InnerXml = _data;
 
            return node;
        }
 
        void TxtFileSave(string _fullPath, List<stTest> _SaveData)
        {
            FileInfo fInfo = new FileInfo(_fullPath);
            FileStream fs = null;
            if (fInfo.Exists)
            {
                fs = fInfo.Open(FileMode.Open);
            }
            else
            {
                fs = fInfo.Create();
            }
            fs.Close();
 
            int index = 0;
            StreamWriter sw = new StreamWriter(_fullPath);
            while (index < _SaveData.Count)
            {
                sw.WriteLine("name :" + _SaveData[index].name);
                sw.WriteLine("sex :" + _SaveData[index].sex);
                sw.WriteLine("age :" + _SaveData[index].age);
                sw.WriteLine("message :" + _SaveData[index].message);
                index++;
            }
            sw.Close();
        }
 
        void TxtFileLoad(string _fullPath, out List<stTest> _LoadData)
        {
            _LoadData = new List<stTest>();
 
            FileInfo fInfo = new FileInfo(_fullPath);
 
            if (fInfo.Exists == false)
            {
                FileStream fs = null;
                fs = fInfo.Create();
                fs.Close();
            }
 
            int index = 0;
            StreamReader sr = new StreamReader(_fullPath);
 
            while (sr.Peek() >= 0)
            {
 
                stTest data = new stTest();
                string line = sr.ReadLine();
 
                if (line.StartsWith("name"))
                {
 
                    data.name = TxtFileReadToData(line);
                }
                else if (line.StartsWith("sex"))
                {
                    string s = TxtFileReadToData(line);
                    if (s == "man")
                    {
                        data.sex = 0;
                    }
                    else if (s == "girl")
                    {
                        data.sex = 1;
                    }
                    else
                    {
                        data.sex = 99;
                    }
                }
                else if (line.StartsWith("age"))
                {
                    string s = TxtFileReadToData(line);
                    data.age = System.Convert.ToInt16(s);
                }
                else if (line.StartsWith("message"))
                {
                    data.message = TxtFileReadToData(line);
                }
 
                _LoadData.Add(data);
            }
 
            sr.Close();
        }
 
        string TxtFileReadToData(string _lineData)
        {
            string data = _lineData;
 
            while (true)
            {
                if (data[0== ':')
                {
                    data = data.Remove(01);
                    break;
                }
                data = data.Remove(01);
            }
 
            return data;
        }
 
        void Save(string _Fullpath)
        {
            Console.WriteLine("Data Save Start");
            switch (eFileType)
            {
                case E_FileType.E_FileType_txt:
                    TxtFileSave(_Fullpath, list_UserData);
                    break;
                case E_FileType.E_FileType_xml:
                    XmlFileSave(_Fullpath, list_UserData);
                    break;
                case E_FileType.E_FileType_json:
                    //JsonFileSave(_Fullpath, list_UserData);
                    break;
                case E_FileType.E_FileType_binary:
                    BinaryFileSave(_Fullpath, list_UserData);
                    break;
                default:
                    Console.WriteLine("No Function");
                    break;
 
            }
            Console.WriteLine("Data Save Complete");
        }
 
        void Load(string _Fullpath)
        {
            Console.WriteLine("Data Load Start");
            switch (eFileType)
            {
                case E_FileType.E_FileType_txt:
                    TxtFileLoad(_Fullpath, out list_UserCopyData);
                    break;
                case E_FileType.E_FileType_xml:
                    XmlFileLoad(_Fullpath, out list_UserCopyData);
                    break;
                case E_FileType.E_FileType_json:
                    // JsonFileLoad(_Fullpath, out list_UserCopyData);
                    break;
                case E_FileType.E_FileType_binary:
                    Console.WriteLine("No Function");
                    break;
                default:
                    Console.WriteLine("No Function");
                    break;
            }
            Console.WriteLine("Data Load Complete");
        }
 
        void DataCreate()
        {
            Console.WriteLine("Data Create Start");
            string message = "hahahahah";
            user1 = TestDataCreate("KimDY""Man"30, message);
            message = "i love you";
            user2 = TestDataCreate("김혜자""Girl"24, message);
 
            list_UserData.Add(user1);
            list_UserData.Add(user2);
 
            message = "new Data";
            user3 = TestDataCreate("만렙""Man"99, message);
            list_UserData.Add(user3);
            //list_UserData.Reverse();
 
            Console.WriteLine("Data Create Complete");
        }
 
        stTest TestDataCreate(string _name, string _sex, int _age, string _message)
        {
            stTest user = new stTest();
            //name
            user.name = _name;
            //sex
            if (_sex == "man" || _sex == "Man" || _sex == "MAN")
            {
                user.sex = 0;
            }
            else if (_sex == "girl" || _sex == "Girl" || _sex == "GIRL")
            {
                user.sex = 1;
            }
            else
            {
                user.sex = 99;
            }
            //age
            user.age = _age;
            //message
            user.message = _message;
            return user;
        }
    }
 
 
}
 
cs