0

I am trying to write byte array content in memory to a file. Here is what I did:

   var bw = new BinaryWriter(File.Open("c:\\Tmp\\" + a.Name, FileMode.OpenOrCreate));
   bw.Write(((FileAttachment)a).Content);

But I find in some cases that I can't manually open the file in 'File Explorer' until I kill my C# which writing the file. Can you please tell me what is that?

Thank you.

3 Answers 3

3

Try closing or disposing the BinaryWriter, e.g.

using (var bw = new BinaryWriter(File.Open("c:\\Tmp\\" + a.Name, FileMode.OpenOrCreate)))
{
   bw.Write(((FileAttachment)a).Content);
}

Also, you might want to use Path.Combine() from now on (it will take care about the backslashes) and use @ to make directory names readable:

Path.Combine(@"c:\Tmp\", a.Name);
Sign up to request clarification or add additional context in comments.

Comments

1

File is locked by your application.
Consider use this reload of the File.Open method that allows you to set the FileShare mode.

using (var bw = new BinaryWriter(File.Open("c:\\Tmp\\" + a.Name, FileMode.OpenOrCreate,
    FileAccess.Write, FileShare.Read))
{
    bw.Write(((FileAttachment)a).Content);
}

Update: thieved from another answer - the using statement.

Comments

1

The BinaryWriter you're creating is locking the file. The file stays locked as long as your program is running because you did not dispose of it.

To do that, you can either dispose of it manually after each use :

var bw = new BinaryWriter(File.Open("c:\\Tmp\\" + a.Name, FileMode.OpenOrCreate));
bw.Write(((FileAttachment)a).Content);
bw.Close();

Use the Using statement which will close the stream automatically:

using (BinaryWriter bw = new BinaryWriter(File.Open("c:\\Tmp\\" + a.Name, FileMode.OpenOrCreate)))
{
    bw.Write(((FileAttachment) a).Content);
}

or even better, use File.WriteAllBytes which handles the writer creation, file opening and stream closing by itself in one concise line :

File.WriteAllBytes("c:\\Tmp\\" + a.Name, ((FileAttachment) a).Content);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.