I need to get all files with prefix 009 from a server path. But my code retrieving all files with 0000 prefix not specifically that starts with 009.
For example, I have files "000028447_ ghf.doc","0000316647 abcf.doc","009028447_ test2.doc","abcd.doc".
string [] files =Directory.GetFiles(filePath,"009*.doc)
is giving me all files except "abcd.doc". But I need "009028447_ test2.doc" instead. If im giving Directory.GetFiles(filePath,"ab*.doc) it will retrieve "abcd.doc", and working as fine.But When im trying to give a pattern like "009"or "00002" it wont work as expected.
Your code snippet is missing a closing quote-character in the pattern. The code should be:
string[] files = Directory.GetFiles(filePath, "009*.doc");
Other than that, it seems to be working as intended. I've tested this by creating a folder with the files you mention in the question:
Next I created a console application, which uses your code to find the files, and prints all the results to the console. The output is the expected result:
C:\\testfolder\\009028447_ test2.doc
Here is the entire code for the console application:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\testfolder";
string[] files = Directory.GetFiles(filePath, "009*.doc");
// Creates a string with all the elements of the array, separated by ", "
string matchingFiles = string.Join(", ", files);
Console.WriteLine(matchingFiles);
// Since there is only one matching file, the above line only prints:
// C:\testfolder\009028447_ test2.doc
}
}
In conclusion, the code works. If you are getting other results, there must be other differences in your setup or code that you haven't mentioned.
If (and I did not check,) it is true that you are only receiving the wrong Files you should maybe use a foreach or linq to check if the Files match your criteria:
Foreach:
List<string> arrPaths = new List<string>();
Foreach(string strPath in Directory.GetFiles(filePath,".doc"))
{
if(strPath.EndsWith(".doc") & strPath.StartsWith("009"))
arrPaths.Add(strPath);
}
Linq:
List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pths => pths.StartsWith("009") && pths.EndsWith(".doc")).ToList();
Both ways are more a workaround than a real solution, but I hope they're helping:)
EDIT
If you want to only get the Filenames i would subtract the filePath from your strPath like this:
Foreach:
arrPaths.Add(strPath.Replace(filePath + "\\", ""));
Linq:
List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pt => pt.StartsWith("009") && pths.EndsWith(".doc")).Select(pths => pths.ToString().Replace(filePath + "\\", "").ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.