3

My program needs to treat some file operations as a unit, some of the important steps in a case are:

  1. delete a file in a directory.
  2. validate some data. if the data is invalid, roll back.
  3. Upload a file to the directory. if upload failed , roll back.
  4. commit changes.

I raise this requirement about transaction is because sometimes a user may use VPN to access my website, the VPN connection maybe very unstable.

If the 3rd step faild, the 1st file and the new uploaded file will all LOST.

some of my code:

        DeleteTheOlderDT(path, FileName);

        this.fuTemplateName.SaveAs(path + FileName);
        _t.FileName = FileName;

        if (!System.IO.File.Exists(path + FileName))
        {
            ArrayList ItemList = new ArrayList();
            ItemList.Add("Uploading failed, please upload again!");
            btlError.DataSource = ItemList;
            btlError.DataBind();
            _t.FileName = "";
            return;
        }
Scott 混合理论
  • 2,263
  • 8
  • 34
  • 59
  • I know I can let the user to upload the file again. But the best way in my case is use transaction like we always do in ado.net. – Scott 混合理论 May 30 '12 at 05:23
  • 1
    I'd rethink the flow of operations to prevent headaches: first of all upload the file in a temporary location, if the upload succeeds validate some data, if the data validates perform the delete & move the uploaded file to the right location. – Alex May 30 '12 at 08:05
  • Possible duplicate of [How to write a transaction to cover Moving a file and Inserting record in database?](https://stackoverflow.com/questions/7939339/how-to-write-a-transaction-to-cover-moving-a-file-and-inserting-record-in-databa) – Ozkan Mar 19 '19 at 11:20

3 Answers3

2

I think you can only do this manually. Look at UnitOfWork from Martin Fowler, you can realize something like he described

Also check this links maybe the help you

Vitaly Zemlyansky
  • 331
  • 1
  • 3
  • 12
1

I never tried it for File system but there is nice article available on code project.

Please take a look http://www.codeproject.com/Articles/31270/A-Transactional-Repository-Implementation-in-NET

Hope it will resolve your problem.

Shailesh
  • 1,178
  • 11
  • 12
1

Windows Vista and newer support Transactional NTFS, which might help you out.

But really, you should consider reworking your logic - upload to a temporary file, and only delete the original file (and rename tempfile) if the upload succeeds.

snemarch
  • 4,958
  • 26
  • 38