應用場景: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; }