How can I change the foldername if there exists some other folder with that name?
I tried in the below manner but it didn’t work 🙁
private int ik;
protected void Button1_Click(object sender, EventArgs e)
{
string folderpath = @"C:\Users\nouser\Documents\Visual Studio 2010\WebSites\folders";
string foldername = TextBox1.Text;
string newPath = System.IO.Path.Combine(folderpath, foldername);
if (Directory.Exists(Path.Combine(folderpath, foldername)))
{
foldername = foldername + Convert.ToString(ik);
ik = ik + 1;
}
else
{
System.IO.Directory.CreateDirectory(newPath);
Response.Write("Folder created");
}
}
This code is able to create a new folder but unable to change the folder name from “newfolder” to “newfolder1” if “newfolder” already exists.
I’m assuming you want something where if you try to create a folder named “foo” but a folder named “foo” exist already you want your new folder to be called “foo1”? If so you’ll have to detect if the folder exists or not and create a new name for it. You can do something like this
This ensures that your new path doesn’t already exist and if it does will ensure you get a unique name for your folder.
In your example I wasn’t sure what you were doing with the variable
I think thats where you were trying to create a unique directory, but what happens if you already have a newFolder1 there? This is why you should use a while loop to keep checking