C#保存已存在相同文件名的文件时,自动追加一个数字以区分同名文件
private void getFileSavaPath(string fileName)
{
string localFilePath = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel表格(*.xlsx)|*.xlsx";
//设置默认文件类型显示顺序
sfd.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
//对话框中默认保存的文件名
sfd.FileName = fileName;
//关闭覆盖警告
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
localFilePath = sfd.FileName.ToString(); //获得文件路径
string directory = Path.GetDirectoryName(localFilePath); //文件所在路径
string filename = Path.GetFileNameWithoutExtension(localFilePath); //文件名
string extension = Path.GetExtension(localFilePath); //文件后缀 带点(.)
int counter = 1;
string newFilename = string.Format("{0}{1}", filename, extension); //文件名+后缀
string newFullPath = Path.Combine(directory, newFilename);
while (File.Exists(newFullPath)) //如果文件存在,如果存在count+1,继续循环
{
newFilename = string.Format("{0}({1}){2}", filename, counter, extension); //文件名+(count)+后缀
newFullPath = Path.Combine(directory, newFilename); //保存路径
counter++; //count+1
}
localFilePath = newFullPath;
StreamWriter sw = File.CreateText(localFilePath);
sw.Close();
}
else
{
//取消操作
}
}