C# 文件的第一行最后一行添加内容

static void AddFileFix(string fileFullName, string prefix, string suffix)
{
    try
    {
        if (string.IsNullOrEmpty(prefix) && string.IsNullOrEmpty(suffix))
        {
            return;
        }

        if (string.IsNullOrEmpty(prefix) && !string.IsNullOrEmpty(suffix))
        {
            FileStream fs_a = new FileStream(fileFullName, FileMode.Append);
            StreamWriter sw_a = new StreamWriter(fs_a);
            sw_a.Write(suffix);
            sw_a.Close();
            fs_a.Close();
            return;
        }

        char[] buffer = new char[10000];

        string renamedFile = fileFullName + ".orig";
        File.Move(fileFullName, renamedFile);

        using (StreamReader sr = new StreamReader(renamedFile))
        using (StreamWriter sw = new StreamWriter(fileFullName, false))
        {
            if (!string.IsNullOrEmpty(prefix))
                sw.Write(prefix);

            int read;
            while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
                sw.Write(buffer, 0, read);

            if (!string.IsNullOrEmpty(suffix))
                sw.Write(suffix);
        }

        File.Delete(renamedFile);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

参考:

https://qa.1r1g.com/sf/ask/70611971/

posted @   double64  阅读(311)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-12-09 OpenCV 创建 Mat 对象的几种方法
2021-12-09 OpenCV 元素数据类型宏名称规律
2021-12-09 OpenCV Mat 类分信息头和像素矩阵指针两部分
点击右上角即可分享
微信分享提示