Does Microsoft provide API for appending binary data to file end?

longevity uyl 285 Reputation points
2024-01-08T10:23:04.7233333+00:00

I can use AppendTextAsync(IStorageFile, String, UnicodeEncoding) to append text to file (https://learn.microsoft.com/en-us/uwp/api/windows.storage.fileio.appendtextasync?view=winrt-22621). Does Microsoft provide API for appending binary data to file end?

Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,305 questions
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,751 Reputation points
    2024-01-08T13:34:36.7266667+00:00

    You can use BinaryWriter:

    using FileStream fs = new FileStream(@".\Test.bin", FileMode.Append, FileAccess.Write);
    using BinaryWriter bw = new BinaryWriter(fs);
    
    bw.Write(new byte[] { 0x01, 0x02, 0x03 });
    bw.Write(new byte[] { 0x04, 0x05, 0x06 });
    

    Note the FileStream has been opened with FileMode.Append.

    0 comments No comments

  2. Junjie Zhu - MSFT 20,441 Reputation points Microsoft Vendor
    2024-01-16T06:34:55.8633333+00:00

    Hi @longevity uyl ,

    Welcome to Microsoft Q&A!

    Due to the file permissions of UWP, it is recommended that you use ApplicationData.Current.LocalFolder to access files in the folder.

    Use OpenStreamForWriteAsync to open stream and use WriteAsync to write binary data to file end.

    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    StorageFile saveFile = await localFolder.CreateFileAsync("FileIOtest.txt", CreationCollisionOption.OpenIfExists);
    
    await FileIO.AppendTextAsync(saveFile, "hello world");
    
    String s = "binary data";
    Byte[] bytes = Encoding.UTF8.GetBytes(s);
    
    using (Stream stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync
        ("FileIOtest.txt", CreationCollisionOption.OpenIfExists))
    {
        stream.Seek(0, SeekOrigin.End);
        await stream.WriteAsync(bytes, 0, bytes.Length);
    }
    

    Thank you.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.