开发者

.NET File Stream write method writes all empty lines

开发者 https://www.devze.com 2022-12-14 12:26 出处:网络
I am having a C# console application access files over a network and write to it. I noticed that some files have been corrupted and have only null written to them. I did not get any exceptions.

I am having a C# console application access files over a network and write to it. I noticed that some files have been corrupted and have only null written to them. I did not get any exceptions. I am using simple code that writes a byte array to the file's stream. When opening the files in Binary mode, all i see are Zeros, something like "0: 00 00 开发者_如何转开发00 00 10: 00 00 00 00".

Does anyone know why such a thing would happen? There could have been a network failure, but network failures should have thrown some IO exceptions right?

Let me know if anyone has any idea about this.

Code sample:

FileInfo fi = new FileInfo(filePath);
using (FileStream fs = fi.Open (FileMode.Create, FileAccess.Write, FileShare.None))
{
   fs.Write(byteData, 0, byteData.Length);
}


Make sure to call FileStream.Flush() where appropriate.


Make sure you're closing the file.


As tzerb above mentioned his code, I thought it would be best to add another layer, a try/catch to check and see if the exception is indeed being caught - I am surprised that no exception occurred but worth a shot

try{
  FileInfo fi = new FileInfo(filePath); 
  using (FileStream fs = fi.Open (FileMode.Create, FileAccess.Write, FileShare.None)) 
  { 
    fs.Write(byteData, 0, byteData.Length); 
    fs.Flush();
    fs.Close();
  }
}catch(System.Security.SecurityException secEx){
  Console.WriteLine("SecurityException caught: {0}", secEx.ToString());
}catch(System.IO.IOException ioEx){
  Console.WriteLine("IOException caught: {0}", ioEx.ToString());
} 

Confirm then if you did indeed get the message 'IOException caught: ...'

Edit: Have added a security exception to see if it has something to do with permissions?

Hope this helps, Best regards, Tom.


That's a new one. My guess is that an exception is getting lost in the downstream code with the FileStream object is destroyed. I'd start by changing the code to do everything explictly:


FileInfo fi = new FileInfo(filePath); 
using (FileStream fs = fi.Open (FileMode.Create, FileAccess.Write, FileShare.None)) 
{ 
    fs.Write(byteData, 0, byteData.Length); 
    fs.Flush();
    fs.Close();
} 

The next thing I'd do is make sure the data you're writing is as expected and then that nothing else is modifying the files.

0

精彩评论

暂无评论...
验证码 换一张
取 消