zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    对比JAVA、Python、C、Go运行时间,我惊呆了!!!
    python中的“反射”
    leetcode最大子序和(python)
    Leetcode228. 汇总区间
    Leetcode204. 计数质数
    Leetcode867. 转置矩阵
    PAT(Advanced Level)A1051. Pop Sequence
    PAT(Advanced Level)A1098.Insertion or Heap Sort
    uniapp关于scroll-view中scroll-into-view的不生效的问题
    HBuilder X 未检测到手机或模拟器
  • 原文地址:https://www.cnblogs.com/yhood/p/11526005.html
Copyright © 2011-2022 走看看