如何使用directory.getfiles获取多个文件名。 [英] How do I get multiple file names with directory.getfiles.
问题描述
大家好:
以下方法是获取某些文件并将其写入1个单独的文件
这是我的代码:
Hi guys :
the following method is to get certain files and will write them into 1 single file
This is my code :
string[] inputFilePaths = Directory.GetFiles("//path to directory", "*.txt.2018-" + DateTime.Now.ToString("MM") + "-*");
using (StreamWriter outputStream = new StreamWriter("path to output file" + DateTime.Now.ToString("MM-yyyy") + "-Statistics.txt",false))
{
foreach (var inputFilePath in inputFilePaths)
{
using (var inputStream = new StreamReader(inputFilePath))
{
outputStream.Write(inputStream.ReadToEnd());
}
}
}
在目录中有以下文件:
TodayLog.txt x
TodayLog.txt.2018-08-08 x
TodayLog.txt.2018-08-09 x
TodayLog.txt.2018-08-10 x
TodayLog.txt.2018-07-29
我只需要用'x'表示的文件。我该怎么办呢?
我尝试过:
In the directory i have the following files :
TodayLog.txt x
TodayLog.txt.2018-08-08 x
TodayLog.txt.2018-08-09 x
TodayLog.txt.2018-08-10 x
TodayLog.txt.2018-07-29
I need only files indicated with an 'x'. How can i do that pleasE?
What I have tried:
var file = Directory.GetFiles("//path to directory").Where(s => s.Equals("TodayLog.txt") || s.Contains(".txt.2018 - " + DateTime.Now.ToString("MM") + "-"));
我试过这个方法,但它没有返回任何东西,我需要返回一个字符串[]。 />
有人可以帮帮我吗?
I tried this method but it is not returning anything and i need the return as a string[].
Someone can help me please?
推荐答案
写一个处理路径的方法:
Write a method to process the path:
private bool IsThisMonth(DateTime now, string path)
{
DateTime dt;
if (!DateTime.TryParseExact(Path.GetExtension(path),
".yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
return false;
}
return dt.Year == now.Year && dt.Month == now.Month;
}
然后它是微不足道的:
Then it's trivial:
DateTime now = DateTime.Now;
string[] thisMonth = inputFilePaths.Where(f => IsThisMonth(now, f)).ToArray();
这篇关于如何使用directory.getfiles获取多个文件名。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!