views:

574

answers:

4

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);
}
+3  A: 

Make sure you're closing the file.

tzerb
The code is within an using block, so file closing should not be the problem. Besides this problem just occurred to a few files, a lot of files have been saved successfully.
Srijanani
+9  A: 

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

Andy West
A: 
tzerb
+2  A: 

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.

tommieb75
This file write code is actually within a try catch block. Let me add the IO exception handler and see if there is anything getting caught.
Srijanani
@Srijanani: Ok, Now that you mentioned it is within the try/catch - I think you should edit your post to include the try/catch. I have thought of something else that could be tripping up...see my edited code above...this is a shooting myself in the foot... :)
tommieb75
@Srijanani: If you still do not see any exception caught in the console, then I am stumped - could be a broken network connection at the point when it writes to the file? What's the filename you are using? Are you using UNC in a verbatim string i.e. @"\\MyServer\foobar.dat"?
tommieb75