0

我想将字节数组附加到现有文件。它必须在文件的末尾。我已经可以设法在文件的开头写了。(感谢stackoverflow ;))。

代码:

public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
   try
   {
      // Open file for reading
      System.IO.FileStream _FileStream = 
         new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                  System.IO.FileAccess.Write);
  // Writes a block of bytes to this stream using data from
  // a byte array.
  _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

  // close file stream
  _FileStream.Close();

  return true;
   }
catch (Exception _Exception)
{
  // Error
  Console.WriteLine("Exception caught in process: {0}",
                    _Exception.ToString());
}

// error occured, return false
return false;

}

从这里得到它:

关联

但我需要在文件末尾

提前致谢。

找到了解决方案:

FileStream writeStream;
        try
        {
            writeStream = new FileStream(_FileName, FileMode.Append,FileAccess.Write);
            BinaryWriter writeBinay = new BinaryWriter(writeStream);
            writeBinay.Write(_ByteArray);
            writeBinay.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
4

1 回答 1

4

而不是使用System.IO.FileMode.Create,使用System.IO.FileMode.Append- 它完全符合您的需要。

来自MSDN 上的FileMode枚举:

Append: Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

于 2013-03-30T19:10:19.793 回答