I have 10 zip files in a folder having path like this
TargetDirectory = "C:\docs\folder\"
some of the zip files names are like this
abc-19870908.Zip
abc-19870908.zip
abc-12345678.zip
and some are like this...
doc.zip
doc123.zip
..
I am getting all file names by using following code...
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
// here I need to compare ,
// I mean I want to get only these files which are having
// these type of filenames `abc开发者_如何学Python-19870908.Zip`
if (filename == "")
{
// I want to do something
}
}
What i have to put in the double quotes in this line if(filename == "")
to get like abc-19870908.Zip
these filenames.
Would any one please suggest any idea about this?
Many thanks...
If you're only interested in zip files containing a dash, you can provide a search pattern to Directory.GetFiles.
string [] fileEntries = Directory.GetFiles(targetDirectory, "*-*.zip");
Check out this link for more information on those search patterns: http://msdn.microsoft.com/en-us/library/wz42302f.aspx
I guess you can do
if (filename.Contains("-"))
{
...
}
if the -
is always present in the filenames you are interested in
or
if (filename.StartsWith("abc-"))
{
...
}
if the filenames always start with abc-
for the ones you are interested in.
you can do if(filename.StartsWith ("abc-") )
or you can do if (filename.Contains ( "-" ) )
or you can do string [] fileEntries = Directory.GetFiles(targetDirectory, "abc-*.Zip");
// Consider using this overload:
// public static string[] GetFiles( string path, string searchPattern)
string [] fileEntries = Directory.GetFiles(targetDirectory, "abc*.zip");
Alternatively, you can use a regular expression as follows:
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
if(Regex.Match (filename, @"abc.*?\.zip", RegexOptions.IgnoreCase))
{
// i want to do something
}
}
List<String> files = Directory.GetFiles(@"C:\docs\folder\").ToList();
var g = from String s in files where s.StartsWith("abc") select s;
foreach(var z in g)
{
//Do stuff in here as a replacement for your if
}
You could use a regular expression that matches your filenames, something along thees lines:
string sPattern = "abc-\d+\.zip";
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
// here i need to compare , i mean i want to get only these files which are having these type of filenames `abc-19870908.Zip`
if(System.Text.RegularExpressions.Regex.IsMatch(filename , sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
// i want to do something
}
}
The regular expression "abc-\d+.zip" means the string "abc-" followed by any number of digits, followed by a . followed by the string "zip" (regular expression syntax)
精彩评论