博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

IO操作

Posted on 2018-05-20 21:25  奋斗ITan_yxing  阅读(90)  评论(0编辑  收藏  举报

1.写入文件

using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        string name = "12345567778890";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        fileStream.Write(bytes, 0, bytes.Length);
                        fileStream.Flush();
                    }
using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        StreamWriter sw = new StreamWriter(fileStream);
                        sw.WriteLine("1234567890");
                        sw.Flush();
                    }

  

using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string msg = "今天是Course6IOSerialize,今天上课的人有55个人";
                        sw.WriteLine(msg);
                        sw.Flush();
                    }

  

using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string name = "0987654321";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        sw.BaseStream.Write(bytes, 0, bytes.Length);
                        sw.Flush();
                    }

2.文件读取

foreach (string result in File.ReadAllLines(fileName))
                    {
                        Console.WriteLine(result);
                    }
                    string sResult = File.ReadAllText(fileName);
                    Byte[] byteContent = File.ReadAllBytes(fileName);
                    string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);

3.大文件读取

using (FileStream stream = File.OpenRead(fileName))//分批读取
                    {
                        int length = 5;
                        int result = 0;

                        do
                        {
                            byte[] bytes = new byte[length];
                            result = stream.Read(bytes, 0, 5);
                            for (int i = 0; i < result; i++)
                            {
                                Console.WriteLine(bytes[i].ToString());
                            }
                        }
                        while (length == result);
                    }