我想知道如何修改我的下面的代码,以便我可以根据文件名确定文件是否已被复制。例如,文件名可能看起来像“Smith,#10 FINAL 08-20-2010.dwg”,如果文件已经重新提交,那么它将看起来像这样的“Smith,#10 FINAL 08-20-2010_1.dwg “或”史密斯,#10 FINAL 08-20-2010_2.dwg“等...注意_1,_2等我需要能够确定该文件是否有_1,_2,_3等复制只有具有最大结束值的文件(假设它有一个)。我只是迷失了如何确定这一点。非常感谢..
//Now lets start searching the entire ARCHIVE folder/subfolders for a DWG that has
//this Well_Name and Actual_Date with FINAL in File Name...
DirectoryInfo myDir = new DirectoryInfo(@"C:\G-M");
//Collect the Final, Approved DWGs only...
var files = myDir.GetFileSystemInfos().Where(f => f.Name.Contains("FINAL") || f.Name.Contains(drow["Well_Name"].ToString()) || f.Name.Contains(drow["Actual_Date"].ToString()));
//Copy to directory...
foreach (FileInfo file in files)
{
//Lets loop through and check to see that the File has greatest value if it contains _1, _2, etc..
System.IO.File.Copy(file.FullName, @"C:\FINAL" + file, true);
}
答案 0 :(得分:1)
使用正则表达式
所以:
string pattern = @"_(\d+)\.dwg";
if (System.Text.RegularExpressions.Regex.IsMatch("file name", pattern, RegexOptions.IgnoreCase))
{ }
编辑:如何做到这一点的想法是:
System.Text.RegularExpressions.Regex myFileRegex = new Regex(@"_(\d+)\.dwg", RegexOptions.IgnoreCase);
SortedDictionary<string, int> fileFromNumber= new SortedDictionary<int, string>();
foreach (string filePath in Direcoty.GetFiles(@"you directory path")
{
Match match = myFileRegex.Match(fileName);
if (match.Groups.Count > 1)
{
fileFromNumber.Add(Convert.ToInt32(match.Groups[1].Value), filePath);
}
}
string newestFile = fileFromNumber[fileFromNumber.Count - 1];//the last element
答案 1 :(得分:0)
此代码应提供您需要的所有内容:
void Main()
{
// this is your base scenario
IEnumerable<FileInfo> fileInfos = new List<FileInfo>{new FileInfo("a_1"), new FileInfo("c"), new FileInfo("a"), new FileInfo("b"), new FileInfo("b_1000")};
// now use the new class
IEnumerable<ComparableFileInfo> cFileInfos = fileInfos.Select(x => new ComparableFileInfo(x));
var nameGroups = cFileInfos.GroupBy(x => x.BaseName).Select(group => new {group.Key, MaxFile = group.Max()});
foreach (var g in nameGroups.OrderBy(x => x.Key))
{
Console.WriteLine(g.MaxFile.OrigFileInfo.FullName);
}
}
class ComparableFileInfo : IComparable{
public FileInfo OrigFileInfo; // omit getters and setters for brevity
public int FileVersion;
public string BaseName;
public ComparableFileInfo(FileInfo fileInfo){
this.OrigFileInfo = fileInfo;
int splitIdx = fileInfo.Name.LastIndexOf("_");
this.BaseName = splitIdx < 0 ? fileInfo.Name : fileInfo.Name.Substring(0, splitIdx);
string version = fileInfo.Name.Substring(splitIdx+1, fileInfo.Name.Length - splitIdx -1);
int versionCast;
this.FileVersion = Int32.TryParse(version, out versionCast) ? versionCast : 0;
}
public int CompareTo(object obj)
{
if (obj is ComparableFileInfo)
{
ComparableFileInfo f2 = (ComparableFileInfo)obj;
return this.FileVersion.CompareTo(f2.FileVersion);
}
else
throw new ArgumentException("Object is not a ComparableFileInfo");
}
}
输出是:
C:\用户\ XXX \桌面\ A_1
C:\用户\ XXX \桌面\ b_1000
C:\用户\ XXX \桌面\ C