I have a File Repository library which handles the saving of files onto the server. Along with saving the physical file, a database entry is also recorded.
Below is the insert method.
public DataFile InsertFile(string fileName, byte[] fileBytes)
{
File.WriteAllBytes(Path.Combine(FileRepPath, fileName), fileBytes);
DataFile dataFile = NewDataFile(
fileName,
fileBytes.Length
);
try
{
using (MyEntities context = new MyEntities())
{
context.DataFiles.Add(dataFile);
context.SaveChanges();
}
}
catch (Exception)
{
File.Delete(Path.Combine(FileRepPath, fileName));
throw;
}
return dataFile;
}
If the database update fails, then I want to delete the file from the server. I do this by catching ANY exception that occurs from the context operations and delete the file (and rethrowing the error so that it can bubble up).
Is this correct practice? Should I be catching more specific exceptions?
DataFilejust before the current user, so you don't want to delete the file from disk.