简体   繁体   中英

Write to file from byte array in c#

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.

Try closing or disposing the BinaryWriter, eg

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);

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM