How to append data to a binary file?

前端 未结 3 1651
Happy的楠姐
Happy的楠姐 2020-11-30 08:51

I have a binary file to which I want to append a chunk of data at the end of the file, how can I achieve this using C# and .net? Also is there anything to consider when wri

相关标签:
3条回答
  • 2020-11-30 09:06

    Using StreamWriter and referencing DotNetPerls, make sure to add the True boolean to the StreamWriter constructor, if otherwise left blank, it'll overwrite as usual:

    using System.IO;
    
    class Program
    {
        static void Main()
        {
        // 1: Write single line to new file
        using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
        {
            writer.WriteLine("Important data line 1");
        }
        // 2: Append line to the file
        using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
        {
            writer.WriteLine("Line 2");
        }
        }
    }
    
    Output
        (File "log.txt" contains these lines.)
    
    Important data line 1
    Line 2
    

    This is the solution that I was actually looking for when I got here from Google, although it wasn't a binary file though, hope it helps someone else.

    0 讨论(0)
  • 2020-11-30 09:16

    You should be able to do this via the Stream:

    using (FileStream data = new FileStream(path, FileMode.Append))
    {
        data.Write(...);
    }
    

    As for considerations - the main one would be: does the underlying data format support append? Many don't, unless it is your own raw data, or text etc. A well-formed xml document doesn't support append (without considering the final end-element), for example. Nor will something like a Word document. Some do, however. So; is your data OK with this...

    0 讨论(0)
  • 2020-11-30 09:23
    private static void AppendData(string filename, int intData, string stringData, byte[] lotsOfData)
    {
        using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None))
        using (var bw = new BinaryWriter(fileStream))
        {
            bw.Write(intData);
            bw.Write(stringData);
            bw.Write(lotsOfData);
        }
    }
    
    0 讨论(0)
提交回复
热议问题