简体   繁体   English

如何使用c#创建按时间顺序的文件夹?

[英]How to create chronological Folder using c#?

When I am saving a file to the filesystem, I need to store it in chronological order (only three level deep). 将文件保存到文件系统时,需要按时间顺序存储(仅三层)。 Year -> Month -> Day -> then store file. 年->月->日->然后存储文件。 (2010 -> June -> 01-06-2010 -> file1.txt. If folders are already in File System then don't create them just save the file. (2010年-> 6月-> 2010年6月1日-> file1.txt。如果文件系统中已存在文件夹,则不要创建文件夹,只需保存文件即可。

Whats the best approach? 什么是最好的方法?

Probably not the best, but a quick one.. Run with c:\\temp, and get C:\\temp\\2010\\juni\\08-06-2010. 可能不是最好的,但是很快。.使用c:\\​​ temp运行,并获得C:\\ temp \\ 2010 \\ juni \\ 08-06-2010。 Locale dependent month name btw.. 取决于语言环境的月份名称

    public static DirectoryInfo GetCreateMyFolder(string baseFolder)
    {
        var now = DateTime.Now;
        var yearName = now.ToString("yyyy");
        var monthName = now.ToString("MMMM");
        var dayName = now.ToString("dd-MM-yyyy");

        var folder = Path.Combine(baseFolder,
                       Path.Combine(yearName,
                         Path.Combine(monthName,
                           dayName)));

        return Directory.CreateDirectory(folder);
    }
DateTime d = DateTime.Now;
String s = Path.Combine(d.Year.ToString(), d.ToString("MMMM"), d.ToString("dd-MM-yyyy"), "file1.txt");
if (!Directory.Exists(s)) Directory.CreateDirectory(s);

For different date formats, this is a good resource: http://blog.stevex.net/string-formatting-in-csharp/ 对于不同的日期格式,这是一个很好的资源: http : //blog.stevex.net/string-formatting-in-csharp/

Obviously, you should combine this path to the main path you will be saving the files in (such as: String s2 = Path.Combine("C:\\\\Test", s); ). 显然,您应该将此路径与将用于保存文件的主路径结合起来(例如: String s2 = Path.Combine("C:\\\\Test", s); )。

string basePath = @"c:\temp";
var myDate = DateTime.Now;
DirectoryInfo di = Directory.CreateDirectory(Path.Combine(basePath, myDate.Year.ToString()));
di = Directory.CreateDirectory(Path.Combine(di.FullName, myDate.ToString("MMMM")));
di = Directory.CreateDirectory(Path.Combine(di.FullName, myDate.ToString("dd-MM-yyyy")));

You can also do it with one CreateDirectory call, in this fashion: 您也可以通过以下一种方式通过一个CreateDirectory调用来做到这一点:

string basePath = @"c:\temp";
var myDate = DateTime.Now;
Directory.CreateDirectory(Path.Combine(Path.Combine(Path.Combine(basePath, myDate.Year.ToString()), myDate.ToString("MMMM")), myDate.ToString("dd-MM-yyyy")));
string StartupPath= @"C:\temp\";
string Year = DateTime.Now.Year.ToString(); 
string Month = DateTime.Now.Month.ToString(); 
string Day = DateTime.Now.Day.ToString();
Directory.CreateDirectory(StartupPath + "\\" + Year + "\\" + Month + "\\" + Day);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM