c# 保存文件名重复,追加,1

应用场景:c#程序生成文件,保存在指定路径中,但路径中已存在有同名的文件,

需要在生成的文件名后追加(1),有(1)则追加(2),自增

  private string 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;
            }
            else {
                add_info_event("取消操作");
            }
       
            return localFilePath;
        }