2

To write a picture on the memory of my pocket pc i use the following code:

pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Append, FileAccess.Write)))
{
    fs.Write(pic);
    fs.Flush();
    continue;
}

I wanted to ask you if this method overwrite the file with new values if the file with this name already exist or do nothing because already exist this file? I need to overwrite the file in eventuality that this file already exist but with old value.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user1788654
  • 311
  • 2
  • 5
  • 13
  • 1
    FileMode.Append appends data if file exists or creates a new file if file doesn't exist. If you want to overwrite the file, use FileMode.Create – Dmitry Bychenko Jul 31 '13 at 10:12

2 Answers2

2

From MSDN FileMode.Create

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

Where as 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.

So, you should use this

pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write)))
       {
          fs.Write(pic);
          fs.Flush();
          continue;
        }
Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

No it appends the lines, you have specified it by writing FileMode.Append, you should specify FileMode.Create in order to append lines (or create a new file if it not exists)

Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69