开发者

GetFiles using path and pattern while ignoring a certain file name in C#

开发者 https://www.devze.com 2023-04-12 07:11 出处:网络
I am trying to get all the .cs files in a certain path. I am doing this using string [] files = Directory.GetFiles(path, pattern);

I am trying to get all the .cs files in a certain path. I am doing this using

string [] files = Directory.GetFiles(path, pattern);

Where path is a valid folder path and pattern is *.cs. However this also returns AssemblyInfo.cs and i dont want that file to be included although it matches the pattern. I want to ignore all the files 开发者_JAVA技巧with the name AssemblyInfo.cs


If you still need it in an array you can do the following:

string[] files = Directory.GetFiles(path, pattern).Where(filename => !filename.EndsWith("AssemblyInfo.cs")).ToArray();

If you don't need it as an array then you can leave off the call to .ToArray() and that will return an IEnumerable<string>.

If you're using a version of .NET that doesn't support Linq (i.e. a version before 3.5) then you can just skip over those parts when you iterate over the array, like so:

string[] files = Directory.GetFiles(path, pattern);
foreach (string filename in files)
{
    if (filename.EndsWith("AssemblyInfo.cs"))
    {
        continue;
    }
}


Most straightforward way would be:

string[] files = Directory.GetFiles(path, pattern).ToList().RemoveAll(f => f.IndexOf("AssemblyInfo.cs", StringComparison.CurrentCultureIgnoreCase) >= 0).ToArray();


there are several options to do that, for example

string[] files = (from x in Directory.GetFiles(path, pattern) where !x.EndsWith ("AssemblyInfo.cs") select x).ToArray();


Assuming you are using .NET 3.5 or higher:

string [] files = Directory.GetFiles(path, pattern).Where(o => Path.GetFileName(o).ToLower() != "assemblyinfo.cs").ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号