Hello World
Hello World

Reputation: 1437

renaming file based on if it exists

I am currently dealing with an issue in iPads were when you upload an image via my site the image is renamed to "image.jpg" which is an issue as if it's in the same directory it can cause issues.. so I am trying to stop it renaming the file OR to add an incremental number onto the end of it, however I can't get this to function correctly.

I have used this small snippet of code to try and fix it, however it doesn't seem to work.

if(File.Exists(filename))
{
    fileName = String.Format("{0}({1}", fileName, count++);
    inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
else
{
    inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
                    }

Upvotes: 1

Views: 1015

Answers (4)

Ehsan
Ehsan

Reputation: 32671

try this

    fileName= Path.Combine(directory,fileName );
    if(File.Exists(filename))
    {
        fileName = fileName + DateTime.Now.Ticks;         
    }
    inputFile.PostedFile.SaveAs( fileName );

Upvotes: 0

Hitesh
Hitesh

Reputation: 3860

You can generate the filename as

filename = filename + DateTime.Now.Ticks.ToString();

so that it will always be the new file. I mean it will retain the old as well as new file.

I hope it will help you.. :)

Upvotes: 1

Lummo
Lummo

Reputation: 1169

When you call:

if(File.Exists(filename))

Make sure that filename includes the full path on disk to where you save the files.

From the looks of it you may want to use Path.Combine(directory, fileName) rather than just filename on its own.

Upvotes: 1

Manish Mishra
Manish Mishra

Reputation: 12375

File.Exists(filename) expects complete file path to see if the file exists or not.

but in the line inputFile.PostedFile.SaveAs, you are concatenating filepath to be

directory + "//" + fileName.

so does your fileName actually consists of fullpath, or just the actual filename with extension?

if fileName consists of fullPath, inputFile.PostedFile.SaveAs should not work, as it would point to invalid location, and if fileName consists of just the file name and not complete path, then, File.Exists should not work. either way your logic is flawed.

I guess, now you know, what to change.

also, instead of using a counter, simply append DateTime.Now.ToString("hhmmddttmmss") to the fileName to make it unique.

Upvotes: 1

Related Questions