我正在开发一个应用程序,该应用程序从特定目录中提取所有文件名的列表,然后需要将文件名解析为多个变量,然后提交给数据库。
如何将字符串文件名解析为多个变量?
EX文件:
2014_31_12_09_36AM_15555555555_108
2014_31_12_09_39AM_108_15555555555
2014_31_12_09_17AM_102_108
文件名包含年,日,月,小时,分钟(带有AM / PM)以及3位或11位数字,后跟另外3位或11位数字
扫描目录后,所有文件名都存储在数组中。
private void ParseFileNames()
{
string Year = "";
string Day = "";
string Month = "";
string Hour = "";
string Minute = "";
string Called = "";
string Calling = "";
//Loop through scanned file names and parse them one at a time.
for (int i = 0; i < fileNames.Length; i++)
{
string[] parsedFileName = fileNames[i].Split('_');
Year = parsedFileName[0];
Day = parsedFileName[1];
Month = parsedFileName[2];
Hour = parsedFileName[3];
Minute = parsedFileName[4];
Called = parsedFileName[5];
Calling = parsedFileName[6];
//open DB connection and submit each individual parsed file data into DB
//Move file from toIndexPath to IndexedPath
}
}
有一个更好的方法吗?
最佳答案
你可以像这样返回一个类
public class FileData
{
public int Year {get;set;}
public int Day {get;set;}
public int Month {get;set;}
public int Hour {get;set;}
public int Minute {get;set;}
public int Called {get;set;}
public int Calling {get;set;}
public FileData(string[] parsedInfo)
{
Year = Convert.ToInt32(parsedInfo[0]);
// and so on with other member to load
}
}
然后只需调用以下命令即可获得
List<FileData>
:var listFileData = fileNames.Select(fn=> new FileData(fn.Split('_'))).ToList();