基本上,我需要检查4版本中是否存在文件,这意味着文件名中出现了11位数的代码。检查完成后,我需要将文件移动到另一台服务器上。
我的问题是我得到了ID,我知道ID出现4次,但我不知道如何从我得到的ID获取文件路径然后移动文件。
任何形式的帮助都将受到超级赞赏。
static void Main(string[] args)
{
string ExtractIDFromFileName(string filename)
{
return filename.Split('_').Last();
}
Dictionary<string, int> GetDictOfIDCounts()
{
List<string> allfiles = Directory.GetFiles("C:/Users/Desktop/Script/tiptop", "*.txt").Select(Path.GetFileNameWithoutExtension).ToList();
allfiles.AddRange(Directory.GetFiles("C:/Users/Desktop/Script/tiptop", "*.top").Select(Path.GetFileNameWithoutExtension).ToList());
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (var x in allfiles)
{
string fileID = ExtractIDFromFileName(x);
if (dict.ContainsKey(fileID))
{
dict[fileID]++;
}
else
{
dict.Add(fileID, 1);
}
}
return dict;
}
var result = GetDictOfIDCounts();
foreach (var item in result)
{
//Console.WriteLine("{0} > {1}", item.Key, item.Value);
if (item.Value == 4)
{
//When we know that those ID appear 4 times, I need to grab back the FilePath and then move the files in an other DIR.
Console.WriteLine("{0} > {1}", item.Key, item.Value);
}
}
Console.ReadLine();
}
你会想要使用File.Move:https://docs.microsoft.com/en-us/dotnet/api/system.io.file.move?view=netframework-4.7.2
这很简单。使字典中的ID成为源文件的完整路径,然后是File.Move(dict.Key,some-variable-holding-the-directory-and-file-name);
由于您将要使用文件路径,只需切换到使用目录和文件的实例版本:DirectoryInfo和FileInfo:
更换
List<string> allfiles = Directory.GetFiles("C:/Users/Desktop/Script/tiptop", "*.txt").Select(Path.GetFileNameWithoutExtension).ToList();
同
DirectoryInfo di = new DirectoryInfo("C:/Users/Desktop/Script/tiptop");
var allFiles = di.GetFiles("*.txt");
使FileInfo成为字典的关键。然后你可以做的事情
dict.Key.FullName
试试这个来获取你想要的文件,它在ID和GroupBy
上使用Count()
。我没有编译它所以可能有错误。
var files = Directory.GetFiles(@"C:\Users\Desktop\Script\tiptop", "*.*")
.Where(file => {
var ext = Path.GetExtension(file).ToLower();
return ext == ".txt" || ext == ".top";
})
.Select(file => new { Path = file, Id = file.Split('_').Last()})
.GroupBy(file => file.Id)
.Where(grp => grp.Count() >= 4)
.SelectMany(x => x)
.Select(x => x.Path);
另一个解决方案是使用Dictionary<string, List<string>>
而不是Dictionary<string, int>
。向Dictionary
添加新密钥时,您可以添加new List<string> { x }
,以便将文件名保留在ID列表中。你可以检查item.Value == 4
列表的大小,而不是检查if
中的item.Count == 4
。然后你仍然有文件名,所以你可以使用它们来移动文件。
希望能帮助到你!