Monday, February 8, 2010

Saving Multiple Files with the Same Name

If you need to save multiple files with the same name in the same directory, a common technique is to construct a file name adding an incremental counter to it, e.g. myfilename(1).txt, myfilename(2).txt, etc.

The method below allows you to create such a file name. It requires 1 parameter: a full file path. The method returns a FileInfo type.
It attempts first to construct a FileInfo object based on a file path, and then checks if such a file already exists. If it does not, the FileInfo object is returned. Otherwise, it constructs a new file name and checks for its existence until such a name no longer exists.

 

private static FileInfo GetFileInfo(string filePath)

{

    FileInfo fInfo = new FileInfo(filePath);

    string fileName = Path.GetFileNameWithoutExtension(filePath);

    string dirName = fInfo.DirectoryName;

    int counter = 1;

 

 

    while (fInfo.Exists)

    {

        string extension = fInfo.Extension;

        string nameProper = fileName + "(" + (counter++) + ")";

        filePath = Path.Combine(dirName, nameProper + extension);

        fInfo = new FileInfo(filePath);

        nameProper = String.Empty;

    }

    return fInfo;

}

2 comments: