[英]How to sort files into Folders by years and months?
I have a program that will save files in .xml
format and have manually added the date when the file is created with System.DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")
. 我有一个程序可以将文件保存为
.xml
格式,并在使用System.DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")
创建文件时手动添加了日期。 An example is like this Scan 2013-07-15 11-13-31 . 例如Scan 2013-07-15 11-13-31 。 I would then need to sort these files that will be generated into folders in the directory of C:\\Users\\name\\Documents\\Scan Archive by years and months.
然后,我需要按年和月排序将要生成的这些文件到C:\\ Users \\ name \\ Documents \\ Scan Archive目录中的文件夹中。
Is this naming convention on the file good to do this sorting? 文件上的这种命名约定是否可以进行这种排序?
How do I start coding for this to sort it into C:\\Users\\name\\Documents\\Scan Archive\\2013 and C:\\Users\\name\\Documents\\Scan Archive\\2013\\Jaunuary and so forth. 如何开始对此进行编码,以将其分类为C:\\ Users \\ name \\ Documents \\ Scan Archive \\ 2013和C:\\ Users \\ name \\ Documents \\ Scan Archive \\ 2013 \\ Jaunuary等等。
public static String GetDirectoryName(DateTime time, String rootpath)
{
String year = String.Format("{0:yyyy}", time);
String month = String.Format("{0:MM}", time) + String.Format("{0:MMM}", time);
String day = String.Format("{0:dd}", time);
String filepath = Path.Combine(rootpath, "y" + year);
filepath = Path.Combine(filepath, "m" + month);
filepath = Path.Combine(filepath, "d" + day);
return filepath;
}
This creates a directory path given a rootpath (such as C:\\users\\name\\Documents\\Scan Archive ) and a DateTime
. 这将在给定根路径(例如C:\\ users \\ name \\ Documents \\ Scan Archive )和
DateTime
创建目录路径。 You'd use the date referenced by your file's name. 您将使用文件名所引用的日期。 Just parse out the file name into a
DateTime
. 只需将文件名解析为
DateTime
。
As others have said in comments, don't use the name of the month unless its after some numeric values. 正如其他人在评论中所说的那样,除非在某些数字值后面加上月份,否则请不要使用月份的名称。 I'd leave it out entirely as I find it slightly verbose.
我会完全忽略它,因为我觉得它有些冗长。
Its easy to tack a file name onto the end of this path, and create all required directories when creating the file. 将文件名添加到此路径的末尾很容易,并在创建文件时创建所有必需的目录。 Problem solved!
问题解决了!
Edit: To create directories while creating some new file: 编辑:要在创建一些新文件时创建目录:
string dirpath = GetDirectoryName(date, "C:\Users\Name");
Directory.CreateDirectory(dirpath);
string filePpath = Path.combine(dirpath,"myfilename.txt");
FileInfo info = new FileInfo(filePath);
info.Create().Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.