0

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?

3
  • This question asks how to catch all entity framework exceptions. forums.asp.net/t/1829033.aspx/1 Commented May 17, 2013 at 5:48
  • Be aware that in case of a system failure you might still end up with the file on disk, but not have the record in the database. Commented May 17, 2013 at 7:16
  • In case of a concurrency exception or a unique constraint violation someone else may have added the DataFile just before the current user, so you don't want to delete the file from disk. Commented May 17, 2013 at 8:25

1 Answer 1

1

I suggest you use the TransactionScope object to manage this task for you. Every component that implements the IEnlistmentNotification interface can participate in a two-phase commit of the TransactionScope.

The commit will require enlisting the services of MS-DTC but it will ensure all or nothing is saved. MS-DTC is used to co-ordinate the results of transactions across multiple heterogeneous resources.

Here are a couple of Microsoft articles:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.