Tintin Santos
Tintin Santos

Reputation: 19

Check if filename exist in the folder directory

Hi I have a code that you can save file and give specific file naming.

the problem is how can I check if file exist in the folder directory.

What I'm trying to do is like this.

               FileInfo fileInfo = new FileInfo(oldPath);
                if (fileInfo.Exists)
                {
                    if (!Directory.Exists(newPath))
                    { 
                        Directory.CreateDirectory(newPath);
                    }
                        fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, extBox1t.Text + "_" + textBox2.Text + "_" + textBox3.Text, fileInfo.Extension));

im trying to add MessageBox.Show in the below

if (!Directory.Exists(newPath))
                    { 
MessageBox.Show("File Exist. Please Rename!");
Directory.CreateDirectory(newPath);

But it does not work. Or is there a way to add extension name at the last part of filename it should like this

Example: STACKOVERFLOWDOTCOME_IDNUM_11162022_0

if STACKOVERFLOWDOTCOME_IDNUM_11162022 exist it will rename to STACKOVERFLOWDOTCOME_IDNUM_11162022_0 it will add _0 at the last part.

Upvotes: 0

Views: 75

Answers (1)

Rufus L
Rufus L

Reputation: 37070

One way to do it is to write a method that extracts the directory path, name, and extension of the file from a string that represents the full file path. Then we can create another variable to act as the "counter", which we'll use to add the number at the end of the file name (before the extension). We can then create a loop that checks if the file exists, and if it doesn't we'll increment the counter, insert it into the name, and try again.

For example:

public static string GetUniqueFileName(string fileFullName)
{
    var path = Path.GetDirectoryName(fileFullName);
    var name = Path.GetFileNameWithoutExtension(fileFullName);
    var ext = Path.GetExtension(fileFullName);
    var counter = 0;

    // Keep appending a new number to the end of the file name until it's unique
    while(File.Exists(fileFullName))
    {
        // Since the file name exists, insert an underscore and number 
        // just before the file extension for the next iteration
        fileFullName = Path.Combine(path, $"{name}_{counter++}{ext}");
    }

    return fileFullName;
}

To test it out, I created a file at c:\temp\temp.txt. After running the program with this file path, it came up with a new file name: c:\temp\temp_0.txt

Upvotes: 1

Related Questions