首页 > 编程语言 >C# 文件的第一行最后一行添加内容

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

时间:2022-12-09 13:47:02浏览次数:59  
标签:第一行 string C# sw prefix 添加 new IsNullOrEmpty suffix

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/

标签:第一行,string,C#,sw,prefix,添加,new,IsNullOrEmpty,suffix
From: https://www.cnblogs.com/huvjie/p/16968692.html

相关文章