如何格式化文件名,包括日期和时间以及月份和年份

Eni*_*ate -1 .net c# filenames file winforms

目前我用来存储像这样的文件名的zip文件...

backup-20111010092345.Zip

但我想将文件名更改为此..backup-2011-10-10_09:23:45.Zip

我有这个代码......

string zipName = Path.Combine(filepath, string.Format("backup-{0}.zip", DateTime.Now.ToString("yyyyMMddhhmmss")));
string backupFilePath = Path.Combine(filepath, backupName);
  using (ZipFile zip = new ZipFile())
  {
    zip.AddFile(backupFilePath, "");
    zip.Save(zipName);

  }



string backupName = "backup.sql";
 string filepath = @"C:\Folder\Back\";
Run Code Online (Sandbox Code Playgroud)

任何人都会对此有所帮助...非常感谢提前...

修改代码:

  string zipName = Path.Combine(filepath, string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip", DateTime.Now));
  string backupFilePath = Path.Combine(filepath, backupName);
  using (ZipFile zip = new ZipFile())
  {
    zip.AddFile(backupFilePath, "");
    zip.Save(zipName);

  }
Run Code Online (Sandbox Code Playgroud)

错误:Notsupported Exception未处理

这是堆栈跟踪.

     at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
   at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
   at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
   at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
   at System.IO.File.Move(String sourceFileName, String destFileName)
   at Ionic.Zip.ZipFile.Save()
   at Ionic.Zip.ZipFile.Save(String fileName)
Run Code Online (Sandbox Code Playgroud)

错误:不支持给定路径的格式.

Jon*_*eet 6

听起来你几乎得到它(在构建你指定的名称方面) - 你只需要更改格式字符串

string zipName = Path.Combine(filepath,
    string.Format("backup-{0}.zip",
                  DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss"));
Run Code Online (Sandbox Code Playgroud)

可以指定为:

string zipName = Path.Combine(filepath,
    string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip",
                  DateTime.Now));
Run Code Online (Sandbox Code Playgroud)

这取决于你发现哪些更具可读性.

请注意,这将使用当前区域性的时间分隔符.如果你总是希望它是"冒号"那么你应该引用它.另一方面,冒号甚至是Windows文件名中的有效字符?考虑再次使用破折号或类似的东西.例如:

string zipName = Path.Combine(filepath,
    string.Format("backup-{0:yyyy-MM-dd_HH-mm-ss}.zip",
                  DateTime.Now));
Run Code Online (Sandbox Code Playgroud)