C# 向文件的最后中添加字节数据以及读取和删除最后的字节数据

有时候保存数据的时候不想额外的搞个配置文件了,就想着能不能直接写到现有的文件中呢,答案是可以的

static void Main(string[] args) {
            try {
                Test();
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("end");
            Console.ReadKey();
        }
        static void Test() {
            string filePath = "E:\\test.jpg";
            SaveInfo(filePath, "info测试123");
            Console.WriteLine(GetInfo(filePath));
        }
        /// <summary>
        /// 向文件流中添加数据
        /// </summary>
        static void SaveInfo(string filePath, string info) {
            using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
                using (BinaryWriter bw = new BinaryWriter(fs)) {
                    fs.Seek(fs.Length, SeekOrigin.Begin);  //默认是从0开始的,需要移动位置,否则会覆盖文件原有数据
                    byte[] bs = Encoding.UTF8.GetBytes(info);
                    bw.Write(bs);
                    bw.Write(bs.Length); //4个字节
                }
            }
        }
        /// <summary>
        /// 从文件流读取并删除数据
        /// </summary>
        static string GetInfo(string filePath) {
            string info;
            using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
                using (BinaryReader br = new BinaryReader(fs)) {
                    var len = fs.Length;
                    fs.Seek(len - 4, SeekOrigin.Begin);  //移动位置,读取信息长度
                    int infoLen = br.ReadInt32();
                    fs.Seek(len - infoLen - 4, SeekOrigin.Begin);
                    info = Encoding.UTF8.GetString(br.ReadBytes(infoLen)); //读取信息
                    fs.SetLength(len - infoLen - 4);  //重新设置文件大小,移除之前添加的额外数据
                }
            }
            return info;
        }

  

posted @ 2021-05-25 11:35  WmW  阅读(829)  评论(0编辑  收藏  举报