Reputation: 139
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);
}
Upvotes: 2
Views: 3950
Reputation: 34592
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.
Upvotes: 2
Reputation: 1433
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.
Upvotes: 0