通过在以前的名称中添加当前日期和时间来重命名文件

时间:2013-08-13 10:34:47

标签: asp.net file file-upload save file-rename

如果文件名已存在于文件夹中,我想重命名用户上传的文件名。

string existpath = Server.MapPath("~\\JD\\");

DirectoryInfo ObjSearchDir = new DirectoryInfo(existpath);
if (ObjSearchFile.Exists)
 {
  foreach (FileInfo fi in ObjSearchFile.GetFiles())
    {
        fi.CopyTo(existfile, false);
     }
  }

此代码无效,无法找到现有文件。

2 个答案:

答案 0 :(得分:1)

这里肯定CopyTo()无效,因为您已将OverWrite选项设置为falseCopyTo()的第二个参数。如果文件存在且overwrite为false,则为IOException按行fi.CopyTo(existfile, false);抛出。检查MSDN

您可以在下面参考两个代码来执行相同的任务。你最喜欢哪一个。任何一个更好的想法?

方法1 :使用File.Copy(), File.Delete()。请参阅MSDN_1& MSDN_2

 string sourceDir = @"c:\myImages";
    string[] OldFileList = Directory.GetFiles(sourceDir, "*.jpg");
        foreach (string f in OldFileList)
        {
            // Remove path from the file name. 
            string oldFileName = f.Substring(sourceDir.Length + 1);
            // Append Current DateTime 
            String NewFileName= oldFileName + DateTime.Now().ToString();
            File.Copy(Path.Combine(sourceDir,oldFileName),
                      Path.Combine(sourceDir,NewFileName);
            File.Delete(oldFileName);
        }

在这种情况下,您可以指定相对路径和绝对路径。相对路径将被视为相对于当前工作目录。

方法2 :使用FileInfo.MoveTo。请参阅MSDN

protected void btnRenameOldFiles_Click(object sender, System.EventArgs e)
  {
    string source = null;                
    //Folder to rename files
    source = Server.MapPath("~/MyFolder/");    
    foreach (string fName in Directory.GetFiles(source)) {
        string dFile = string.Empty;
        dFile = Path.GetFileName(fName);
        string dFilePath = string.Empty;
        dFilePath = source + dFile;
        FileInfo fi = new FileInfo(dFilePath);
            //adding the currentDate
        fi.MoveTo(source + dFile + DateTime.Now.ToString());
    }       
}

答案 1 :(得分:0)

this文章中,CopyTo方法仅设置是否要覆盖现有文件。您应该做的是使用以下命令检查目标目录中是否存在该文件:

File.Exists(path)

如果是的话,你需要重命名你正在使用的文件(我不确定你得到的ObjSeachFile对象是什么),然后尝试重新保存它。另外请记住,如果您有另一个具有相同名称的现有文件,则应重新检查该文件是否存在。

相关问题