返回一个可用的名称如1_4.txt
private string GetCanUseName(string newName,string oldName,int num)
{
if (!File.Exists(newName))
{
return newName;
}
else
{
//存在
string ext = Path.GetExtension(oldName);
string nameInfo = oldName.Replace(ext, "");
return GetCanUseName(nameInfo + "_" + (++num) + ext, oldName, ++num);
}
}
private void button1_Click(object sender, EventArgs e)
{
string name = "C:\\123\\1.txt";
string tt = GetCanUseName(name, name, 0);
MessageBox.Show(tt);
}
{
if (!File.Exists(newName))
{
return newName;
}
else
{
//存在
string ext = Path.GetExtension(oldName);
string nameInfo = oldName.Replace(ext, "");
return GetCanUseName(nameInfo + "_" + (++num) + ext, oldName, ++num);
}
}
private void button1_Click(object sender, EventArgs e)
{
string name = "C:\\123\\1.txt";
string tt = GetCanUseName(name, name, 0);
MessageBox.Show(tt);
}