views:

42

answers:

2

Hi guys,

in a windows environment and in several applications, when we create a new file with the same name of an existing file, the user is not prompted with a message that the output file already exists, but it creates a new file with (1) at the end of the filename...

name.doc

will be

name(1).doc

I'm trying to create the same behavior in C# and my question is... can I reduce all this code?

FileInfo finfo = new FileInfo(fullOutputPath);
if (finfo.Exists)
{
  int iFile = 0;
  bool exitCreatingFile = false;
  while (!exitCreatingFile)
  {
    iFile++;
    if (fullOutputPath.Contains("(" + (iFile - 1) + ")."))
        fullOutputPath = fullOutputPath.Replace(
                "(" + (iFile - 1) + ").",
                "(" + iFile + ").");  // (1) --> (2)

    else
        fullOutputPath = fullOutputPath.Replace(
                Path.GetFileNameWithoutExtension(finfo.Name),
                Path.GetFileNameWithoutExtension(finfo.Name) + "(" + iFile + ")"); // name.doc --> name(1).doc

    finfo = new FileInfo(fullOutputPath);
    if (!finfo.Exists)
        exitCreatingFile = true;
  }
}
+2  A: 

I've written a Winforms control that handles most of the details of a file menu implementation. I don't think it uses less code (though the implementaiton is different), but you may want to take a look.

FileSelect control

peterchen
thxs, I will have in mind when developing WinForms!
balexandre
+2  A: 

How about (without adding any further exception handling around the FileInfo constructor):

FileInfo finfo = new FileInfo(fullOutputPath);
int iFile = 1;
while (finfo.Exists)
{
    finfo = new FileInfo(
        Path.GetFileNameWithoutExtension(fullOutputPath) +
        "(" + iFile + ")" +
        Path.GetExtension(fullOutputPath));
    iFile++;
}
// Optionally add fullOutputPath = finfo.Name; if you want to record the final name used
jerryjvl
much cleaner :) thanks
balexandre
Definitely better than the original method. I see no reason to separately store the name though, as it's available from the FileInfo object.
Daniel Straight
Didn't know whether `fullOutputPath` may still be used further on, since his original code specifically was updating it in-place.
jerryjvl