Can I optimize the code, without using a foreach loop? The objective is to find files having a .config extension and replace a specified text before deploying it into production.
DirectoryInfo di= new DirectoryInfo(@"C:\Inetpub\Wwwroot\workframew\Presentation\Website");
FileInfo[] fl= di.GetFiles("*.config");
foreach (FileInfo fi in fl)
{
//File.Replace(fi.FullName,fi.FullName,.ReadAllText(fi.FullName) = File.ReadAllText(fi.FullName).Replace(@"F:\LogFiles\ApplicationLogs\Compass\",@"C:\Compass_350\Compass\");
string filePath = fi.FullName;
StreamReader reader = new StreamReader(filePath);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, @"F:\LogFiles\ApplicationLogs\Compass\", @"C:\Compass_350\Compass\");
StreamWriter writer = new StreamWriter(filePath);
writer.Write(content);
writer.Close();
}
As of .NET 4,
Directory.EnumerateFileshas an overload that will allow you to search for a pattern and optionally all subdirectories. In earlier versions- v2 or later- (or if you’d prefer a method that returns an array of strings), you can useDirectory.GetFilesthat works similarly. The difference is the former returnsIEnumerable<string>, while the latter returns an array of strings.However, you’ll still have to transform the files yourself, so all those methods save you is having to build a recursive structure, which is still worthwhile. Additionally, you’ll need to escape regular expression special characters so the string you are searching (the directory path) will be found literally, unless the expression is intended (in this case, it’s obvious you want the path to be found literally, so the backslashes must be escaped).