Check and rename file variable

G

Guest

Hi, I’ve written a c# program to compact certain msaccess databases. The way
this works is to compact say C:\test1.mdb to C:\temp.mdb, then delete
C:\test1.mdb and rename C:\temp.mdb as C:\test1.mdb.

My problem occurs if there is already a C:\temp.mdb file. I don’t want to
just delete this, as it could have been created separately by a user.

In my code, I set a constant as follows:

private const string tempMdb = @"C:\temp.mdb";

To check that the file exists, I can use

if (File.Exists(tempMdb))...

but, if it is present, how do I change the tempMdb to a unique name?

I.e. if C:\temp.mdb is present, then rename as C:\temp1.mdb,
if C:\temp1.mdb is present, then rename as C:\temp2.mdb,
if C:\temp2.mdb is present, then rename as C:\temp3.mdb.....

I realise some sort of looping maybe required here but I’m not sure on the
best approach.

Thanks in advance.
 
O

Ollie Riches

beaware that simply just using a File.Exists to check that a file exists
before you attempt to create a file can suffer from a race condition if some
other process creates the file between you checking for the existence of the
file and you create an instance of a file with the required filename.

HTH

Ollie Riches
 
J

JohnnyAppleseed

When going a file a unique name, I typically format the current date/time as
a string (yyyymmdd-hhmmss) and then append that to the file name. This
naming convention would be both unique and meaningful. For example:
temp_20050215-113045.mdb
 
A

Adam Clauss

Check out System.IO.Path.GetTempFileName().

As this call will also create the file, you may have to delete it prior to
compacting.
Ex:

string dbPath = "myDatabase.mdb";
string tempPath = Path.GetTempFileName();
File.Delete(tempPath); //0 byte file created by GetTempFileName

//compact database

File.Delete(dbPath);
File.Move(tempPath, dbPath);
 
G

Guest

Thanks for the help. I tried to use the GetTempFileName(), however the file
that is created is tmp450.tmp and I think it needs to be an mdb file.Is there
some way to use the GetTempFileName() method to create an access mdb file?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top