c# 保存文件名重復,追加(1)(2)......


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM