473,396 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Rolling back file errors

Once file is open, it should be closed:

Stream fs = new FileStream(filename, FileMode.Create);
try {
// write, exceptions may raise here
} finally {
fs.Close();
}

What should one do to remove the file in case of an error?

May 8 '07 #1
8 1744
What should one do to remove the file in case of an error?

Stream fs = new FileStream(filename, FileMode.Create);
try
{
//do sth
}
catch (IOException)
{
//sth went wrong
File.Delete(filename);
}
finally
{
fs.Close()
}
May 8 '07 #2
On May 8, 2:13 pm, "TS25" <x...@xxx.comwrote:
What should one do to remove the file in case of an error?

Stream fs = new FileStream(filename, FileMode.Create);
try
{
//do sth}

catch (IOException)
{
//sth went wrong
File.Delete(filename);}

finally
{
fs.Close()

}
That's unlikely to work, as you'll be closing the filestream *after*
trying to delete the file - I'd expect the call to File.Delete to
fail. Either close the stream in the catch block directly as well, or
keep a flag of whether or not to delete the file, set it in the catch,
and do it in the finally.

Jon

May 8 '07 #3
"TS25" <xx*@xxx.comwrote in message
news:eW**************@TK2MSFTNGP02.phx.gbl...
>What should one do to remove the file in case of an error?

Stream fs = new FileStream(filename, FileMode.Create);
try
{
//do sth
}
catch (IOException)
{
//sth went wrong
File.Delete(filename);
}
finally
{
fs.Close()
}


This will not work as you can't delete a file which is still open. So,
you'll have to close the file before calling Delete.
What you can do is set a flag in the catch handler, in the finally clause
you can check the flag ( after calling Close) and delete the file when set .

Willy.

May 8 '07 #4
fail. Either close the stream in the catch block directly as well, or
keep a flag of whether or not to delete the file, set it in the catch,
and do it in the finally.
Peahaps I misunderstand your idea, but I contrive to do it vice-versa -- set
up the flag in finally and rollback in catch:

enum RollbackMarker {none, file, db_record};
RollbackMarker rbm = RollbackMarker.none; // rollback marker
try {
// create a file
Stream fs = new FileStream(name, FileMode.Create);
try {
// write file
} finally {
fs.Close(); // first, we must close the file
rmb = RollbackMarker.file; // 2nd, we must remove it if
failure
}

// add DB entry
Entry entry = db.insert(data);
rbm = RollbackMarker.db_record;

.. make more construction-allocations

} catch (Exception e) {
// failure, rollback the allocations
log("rolling back since " + rbm);
switch (rbm) {
...
case RollbackMarker.db_record: File.Delete(); goto case
RollbackMarker.file; // why the hell did MS refuse the downfalls?
case RollbackMarker.file: db.remove(entry); break;
}
throw; // re-throw
}
Note, the rollback marker in the finally section.Whether file I/O success or
error we must complete the file creation by closing it and and note that the
file has been created. Resources must be closed only if their
constructor/allocator has succeeded.Therefore, I set up the marker after
construction.
May 8 '07 #5
valentin tihomirov <V_*********@best.eewrote:
fail. Either close the stream in the catch block directly as well, or
keep a flag of whether or not to delete the file, set it in the catch,
and do it in the finally.

Peahaps I misunderstand your idea, but I contrive to do it vice-versa -- set
up the flag in finally and rollback in catch
That seems significantly more complicated to me.

Oh, and MS removed fallthrough in switch cases because almost all
occurrences of it in languages which allow it are accidental rather
than deliberate. Admittedly switch should have been radically
overhauled anyway, but never mind...

If you want your enum to effectively have flags as to whether to remove
the file and whether to remove the database record, then *implement* it
as a flags enum, with 1=file, 2=db_record and the implicit 3=both. (I'd
also recommend using .NET naming conventions, but that's just an
aside.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 8 '07 #6
Personally, I'd do something like this:

public struct FileRollback : IDisposable
{
// The file name.
private string filename;

// Store the file.
public FileRollback(string filename)
{
// Set the file.
this.filename = filename;

// Delete by default.
rollback = true;
}

// Rollback the file?
private bool rollback;

public void Commit()
{
// Do not rollback the file.
rollback = false;
}

public void Dispose()
{
// If rolling back the file, delete here.
if (rollback)
{
// Delete.
File.Delete(filename);
}
}
}

Then, in the client code:

// Create the rollback.
using (FileRollback fileRollback = new FileRollback(filename))
using (Stream fs = new FileStream(filename, FileMode.Create))
{
// Do your work.

// Do not delete the file at this point.
fileRollback.Commit();
}

This way, if an exception is thrown, the file is deleted, if not, the
file remains. It also cleans up the code a great deal.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP********************@msnews.microsoft.com.. .
valentin tihomirov <V_*********@best.eewrote:
fail. Either close the stream in the catch block directly as well, or
keep a flag of whether or not to delete the file, set it in the catch,
and do it in the finally.

Peahaps I misunderstand your idea, but I contrive to do it vice-versa --
set
up the flag in finally and rollback in catch

That seems significantly more complicated to me.

Oh, and MS removed fallthrough in switch cases because almost all
occurrences of it in languages which allow it are accidental rather
than deliberate. Admittedly switch should have been radically
overhauled anyway, but never mind...

If you want your enum to effectively have flags as to whether to remove
the file and whether to remove the database record, then *implement* it
as a flags enum, with 1=file, 2=db_record and the implicit 3=both. (I'd
also recommend using .NET naming conventions, but that's just an
aside.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

May 9 '07 #7
That seems significantly more complicated to me.

Of course, if you have only one object to rollback a bit flag suffices to
you. I have presented a whole framework to rollback all allocations till
error point. It conforms the construction-deconstruction framework I
proposed in this incomplete blogg:
http://valjok.blogspot.com/2007/05/r...cessfully.html

>
Oh, and MS removed fallthrough in switch cases because almost all
occurrences of it in languages which allow it are accidental rather
than deliberate. Admittedly switch should have been radically
overhauled anyway, but never mind...
"Accidential" means here a "naturally simple grammar". Now, you add an
artificial barrier adding a level of complexity into grammar in order to
preclude user freedom. For me it looks like you had a natural direct access
from A to B and after adding some restricting rules you should explicitly
ensure every movement. Direct access means you can write less code, less
effort to reach some goal. Not sure the overcomplication worth breaking this
natural goodness.
May 9 '07 #8
I have did it this way:

Stream tempFile = createfile();
try {
try {
// fill with data
} finally { // always close first
tempFile.Close();
}
// use
} finally { // always remove the closed file
File.Remove(tempFile.Name); // always remove the closed file
}
Actually, I required a bit more complex task:

Stream tempFile = createfile();
try {
try {
//fill with data
} finally { // always close first
tempFile.Close();
}

// process the file deriving its persistent name
// File.Move(tempFile, persistentName);
} catch { // remove the file if it has failed to rename
File.Remove(tempFile.Name);
throw;
}
The only consern is if renaming succeeded but an error occured nevertheless.
Is it possible?
Jul 25 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: deko | last post by:
I use this script to keep count of visits to my site - it's on every page in the site. <?php $file = '/home/post/public_html/viscount'; if ($counter = @file ($file)) { $line = each($counter);...
9
by: Marcus | last post by:
Hello, Say I have a function with 5 MySQL queries that all insert or update the database. Now let's assume that during execution, the first 3 queries are executed fine but then the 4th one dies...
6
by: nwheavyw8 | last post by:
I am currently trying to write a simple PHP script that will split an uploading file up into 500kb "chunks", then read and concatenate them back together when accessed for download. I can't seem...
3
by: DB2 Convert | last post by:
Hi, Correct me if I am wrong? Why should I specify at the restore statement such as Restore Database ABC ... "WITHOUT ROLLING FOWARD"? My understand is when I am using circular logging,...
101
by: Elijah Cardon | last post by:
Let's say I have m dice having n sides, such that n^m is not going to bust int as a datatype. With m=4 and n=6, an outcome might be {2, 5, 1, 2}. What is a good way to represent this in c so that...
17
by: Jose Durazo | last post by:
Hello, I'm doing an exercise to simulate rolling a pair of dice 36,000 times, then count and display how many times the simulation rolls each possible sum. For some reason each time I run my...
3
by: farhadtarapore | last post by:
I have a very large C++ application that has been converted into a windows service. This application writes a lot of statements to the console i.e. cout and cerr. I have used std::ofstream...
4
by: brendan.wong | last post by:
hello. i'm trying to incorporate error handling into my application, but i've run into a dilemma. i've already performed 10 successful INSERTS, but on the 11th INSERT, the application fails for...
12
by: jim.richardson | last post by:
Hi all, I'd like a page to be excluded from the back button history, that is, when a user hits their browser's back button, it never backs into this particular page. Can anybody please tell...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.