追加时间戳的文件名 [英] Append TimeStamp to a File Name

查看:631
本文介绍了追加时间戳的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也碰到过这个问题多次在这我想有多个版本在同一目录中相同的文件。在路上我一直在做它用C#是通过添加时间戳的文件名像这样 DateTime.Now.ToString()更换('/',' - ')。更换( ':')。。 有没有更好的方式来做到这一点?

I have come across this problem several times in which I would like to have multiple versions of the same file in the same directory. The way I have been doing it using C# is by adding a time stamp to the file name with something like this DateTime.Now.ToString().Replace('/', '-').Replace(':', '.'). Is there a better way to do this?

推荐答案

您可以使用则DateTime.ToString方法(字符串)

DateTime.Now.ToString(yyyyMMddHHmmssfff)

的String.Format

的String.Format({0:YYYY-MM-dd_hh-MM-SS-TT},DateTime.Now);

有以下的自定义格式说明年(年),M(月),D   (天)中,h(小时12),H(小时24),米(分钟),s(秒)中,f(第二   分数),F(第二部分,结尾零修剪),T(PM或   A.M)和Z(时区)。

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

随着扩展方法

用法:

string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt

扩展方法

public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

这篇关于追加时间戳的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆