winforms 如果文件名存在,则在文件末尾添加扩展名[duplicate]

ssm49v7z  于 2022-12-14  发布在  其他
关注(0)|答案(4)|浏览(151)

此问题在此处已有答案

Automatically increment filename(9个答案)
昨天关门了。
如果文件存在于文件夹和数据库中,如何在文件名末尾添加扩展名?
例如,如果存在如下文件名:

JOHN_DENVER_SMITH.pdf

代码应将第二条记录重命名为JOHN_DENVER_SMITH_(1).pdf
下面是我的代码:

FileInfo fileInfo = new FileInfo(oldPath);

if (fileInfo.Exists)
{
    try
    {
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }

        fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, firstname.Text + "_" + midlename.Text + "_" + lastname.Text, fileInfo.Extension));
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    }
}
ycggw6v2

ycggw6v21#

验证新位置上是否已存在该文件。如果存在,请在文件名末尾添加计数器值,然后重试。重复此操作,直到文件名不存在。

FileInfo fileInfo = new FileInfo(oldPath);

if (fileInfo.Exists)
{
    try
    {
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }
        
        var newFileName = string.Format("{0}{1}{2}", newPath, firstname.Text + "_" + midlename.Text + "_" + lastname.Text, fileInfo.Extension);
        var i = 0;
        while (File.Exists(newFileName))
        {
            newFileName = string.Format("{0}{1}_({2}){3}", newPath, firstname.Text + "_" + midlename.Text + "_" + lastname.Text, ++i, fileInfo.Extension);
        }

        fileInfo.MoveTo(newFileName);
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    }
}
rqqzpn5f

rqqzpn5f2#

试试这个:

static string GetFilePath(string path)
{
  // do nothing if file not exists
  if(!File.Exists(path)) return path;
  
  int index = path.LastIndexOf(".");
  var ext = index == -1 ? String.Empty : path.SubString(index);
  var pathNoExt = index == -1 ? path : path.SubString(0, index);
  
  int i = 0;
  string result = null;
  
  // Loop until the file does not exist
  while(File.Exists(result = $"{pathNoExt}({++i}){ext}"));
  return path;
}

用法:

fileInfo.MoveTo(GetFilePath($"{newPath}{firstname.Text}_{midlename.Text}_{lastname.Text}{fileInfo.Extension}"));

您可以将string替换为ReadOnlySpan<char>,将SubString替换为Slice,以获得更好的性能。

voase2hg

voase2hg3#

您可以编写代码来生成新路径,如下所示。

private string NewPathFor(string oldPath)
{
     var fileInfo = new FileInfo(oldPath);
     var newPath = oldPath;
     for (var i = 0; !fileInfo.Exists; i++)
     {
         newPath = $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}_({i}).{fileInfo.Extension}";
         fileInfo = new FileInfo(newPath);
     }
     return newPath;
}

然后叫它,

var oldPath=$"{firstname.Text}_{midlename.Text}_{lastname.Text}.pdf";
  fileInfo.MoveTo(NewPathFor(oldPath));
  dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
aoyhnmkz

aoyhnmkz4#

如果不存在(IO.File.Exists(fileName &“(“& fileNumber.ToString &“)”& fileExtension),则'文件不存在,执行某些操作.. Exit Do Else '文件确实存在,因此递增并尝试下一个...

相关问题