如何在文件名中搜索符号?
问题描述:
亲爱的专家,
问题:批量上传文件后,我需要按名称识别和排序文件(通过掩码或标记)。例如,文件名Tripolskoe_23_2341_MD_123-XXX.PDF。我的实用程序应识别文件名,并根据MD标志确定此文件。应该提供什么样的搜索条件?在我的情况下我可以用什么代码?
问候,
Darya
我有什么试过:
Dear Experts,
Problem: after the batch uploading files I need to recognizing and sorting files by names (by mask or flag). For example, file name "Tripolskoe_23_2341_MD_123-XXX.PDF". My utility should recognize the file name and determine this file per flag "MD". What condition for search should be put? What code I can use in my case?
Regards,
Darya
What I have tried:
private void DropSpot_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
// We only want to accept files, so we only set our DragDropEffects
// if that's what's being dragged in
if (e.Data.GetDataPresent(DataFormats.FileDrop, false)==true)
{
e.Effect = DragDropEffects.All;
}
}
ArrayList Files = new ArrayList();
private void DropSpot_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
// Get a list of all objects in the Drop Data, that are files
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
// Iterate through the dropped files
for (int i=0;i<files.Length;i++)
{
// Add the to our ArrayList
Files.Add(files[i]);
// Create our new List View item
ListViewItem item = new ListViewItem();
// Get a file info object
// we use this for getting file size, etc.
System.IO.FileInfo fInfo = new System.IO.FileInfo(files[i]);
item.Text = System.IO.Path.GetFileName(fInfo.Name);
item.SubItems.Add(fInfo.Length.ToString());
item.SubItems.Add("Pending");
FileListView.Items.Add(item);
FileListView.Tag = Files[Files.Count-1];
}
// Refresh the file list - for good measure
this.Refresh();
// If we added files, clear the instruction label
}
答
这将取决于文件名的组织方式。如果它们总是采用相同的格式:
It's going to depend on how your file names are organised. If they are always in the same format:
aaa_dd_dddd_BitYouWant_ddd-aaaa.extension
那么最简单的方法就是使用Split:
Then the simplest way is just to use Split:
string[] parts = filename.Split('_');
if (parts.Length == 5)
{
string bitYouWant = parts[3];
...
}