C# IO和序列化

文件目录

相关类

  • DirectoryInfo
  • Direcoty
  • FileInfo
  • File

相关操作API:

  • Create
  • Exists
  • MoveTo
  • Open

文件相关属性

  • Name
  • FullName
  • CreationTime
  • Attributes

流 IO

定义

流代表在源文件和目标文件之间传输一定量的数据
通过流访问网络,内存地址,和其它与流相关的设备

常用流类

FileStream 读取和写入一个字节或者字节数组

         static void TestFileStream()
        {
            using (FileStream fs = File.Open("msg.dat", FileMode.Create))
            {
                string msg = "hello";
                byte[] msgByteArray = Encoding.Default.GetBytes(msg);
                fs.Write(msgByteArray, 0, msgByteArray.Length);

                fs.Position = 0;

                byte[] byteFromFile = new byte[msgByteArray.Length];
                for(int i = 0; i < msgByteArray.Length; i++)
                {
                    byteFromFile[i] = (byte)fs.ReadByte();
                    Console.Write(byteFromFile[i]);
                }
            }
        }
        
 

StreamWriter 基于字符的读写流

        static void TestStreamWriter()
        {
            using (StreamWriter writer = File.CreateText("test.txt"))
            {
                writer.WriteLine("hello");
                writer.WriteLine("world");
                writer.WriteLine("its a test file create by streamwriter");
            }
        }
        
        /// 
        /// 将文本信息当作内存中的字符一样处理
        /// 
        static void TestStreamReader()
        {
            using (StreamReader reader = File.OpenText("test.txt"))
            {
                string input = null;
                while((input == reader.ReadLine()))
                {
                    Console.WriteLine(input);
                }
            }
        }   

StreamReader 将文本信息当作内存中的字符一样处理

        static void TestStreamReader()
        {
            using (StreamReader reader = File.OpenText("test.txt"))
            {
                string input = null;
                while((input == reader.ReadLine()))
                {
                    Console.WriteLine(input);
                }
            }
        }
        
        
        static void TestStringWriter()
        {
            using (StringWriter writer = new StringWriter())
            {
                writer.WriteLine("hahhhhh ");
                writer.WriteLine("aaaaaa ");
                Console.WriteLine(writer);

                Console.WriteLine("----------");
                using (StringReader reader = new StringReader(writer.ToString()))
                {
                    string input = null;
                    while((input = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(input);
                    }
                }
            }
        }

BinaryWriter 二进制格式读写数据流,支持随机数据访问 Seek

 static void TestBinaryWriter()
        {
            FileInfo f = new FileInfo("BinFile.dat");
            using(BinaryWriter bw = new BinaryWriter(f.OpenWrite()))
            {
                Console.WriteLine(bw.BaseStream);

                double aDouble = 12233.22;
                int anInt = 1022;
                string aString = "a,b,c";
                bw.Write(aDouble);
                bw.Write(anInt);
                bw.Write(aString);
            }

            Console.WriteLine("Done!");
           
        }

        static void TestBinaryReader()
        {
            FileInfo f = new FileInfo("BinFile.dat");
            using (BinaryReader br = new BinaryReader(f.OpenRead()))
            {
                Console.WriteLine(br.ReadDouble());
                Console.WriteLine(br.ReadInt32());
                Console.WriteLine(br.ReadString());
            }
        }

观察文件变动 FileSystemWatcher

        static void TestFileWatcher()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            try
            {
                watcher.Path = ".";

            }
            catch(ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            watcher.NotifyFilter = NotifyFilters.LastAccess
                | NotifyFilters.LastWrite
                | NotifyFilters.DirectoryName
                | NotifyFilters.FileName;

            //只观察文本文件
            watcher.Filter = "*.txt";

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            //开始观察目录
            watcher.EnableRaisingEvents = true;

            Console.WriteLine(@"Press 'q' to quit app.");
            while (Console.Read() != 'q') ;
                
        }

        static void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File:{0} {1}", e.FullPath, e.ChangeType);
        }

        static void OnRenamed(object source, RenamedEventArgs e)
        {
            Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
        }

序列化

定义

持久化一个对象的状态到流(文件流和内存流)的过程。

BinaryFormatter 二进制序列化

    static void TestSerialize()
    {
        UserPref userData = new UserPref();
        userData.WindowColor = "Red";
        userData.FontSize = 50;
    
        BinaryFormatter binFormat = new BinaryFormatter();
        using(Stream fStream = new FileStream("user.dat", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            binFormat.Serialize(fStream, userData);
        }
    }


    static void LoadFromBinaryFile()
    {
        BinaryFormatter binFormat = new BinaryFormatter();
        using (Stream fStream = File.OpenRead("user.dat"))
        {
            UserPref userData = (UserPref)binFormat.Deserialize(fStream);

            Console.WriteLine("UserPref {0},{1}", userData.WindowColor, userData.FontSize);
        }

    }
    
    [Serializable]
    public class UserPref
    {
        public string WindowColor;
        public int FontSize;
    }


    //参与序列化,不可继承
    [Serializable]
    public class Radio
    {
        public bool hasTweeners;
        public bool hasSubWoofers;
        public double[] stationPresets;

        //不参与序列化
        [NonSerialized]
        public string radioID = "XF-3344";
    }    

你可能感兴趣的:(C# IO和序列化)