如果存在具有该名称的其他文件夹,如何更改foldername
?
我尝试了以下方式,但它不起作用:(
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");
}
}
如果“newfolder”已经存在,此代码可以创建新文件夹但无法将文件夹名称从“newfolder”更改为“newfolder1”。
答案 0 :(得分:5)
我假设你想要一些东西,如果你试图创建一个名为" foo"但是一个名为" foo"的文件夹已经存在你想要你的新文件夹被调用" foo1"?如果是这样,您必须检测文件夹是否存在,并为其创建新名称。你可以做这样的事情
var count = 1;
var originalPath = newPath;
while(Directory.Exists(newPath)){
newPath = originalPath + count;
count++;
}
Directory.CreateDirectory(newPath);
这可确保您的新路径不存在,如果确实存在,则可确保您获得文件夹的唯一名称。
在你的例子中,我不确定你用变量
做了什么ik
我认为那是你尝试创建一个独特目录的地方,但是如果你已经有一个newFolder1会发生什么?这就是为什么你应该使用while循环来继续检查
答案 1 :(得分:2)
使用system.IO.Directory move
System.IO.Directory.Move("newfolder","newfolder1");
有关详细信息,请参阅msdn:
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
答案 2 :(得分:1)
使用像这样的移动:
System.IO.Directory.Move("old name", "new name");