1

ディレクトリ内のすべての *.config ファイルと、文字列 MySettings.xru を含むそのサブディレクトリを取得する必要があります。

見つかったすべてのファイルで、文字列 MySettings.xru を含む行だけで、テキスト db001 を db002 に置き換える必要があります。

したがって、たとえば、次の場合:

RandomSettings.xru someOtherWords Database=db001 blah, blah, blah...
MySettings.xru Lalala Database=db001 blah, blah, blah...
YourSettings.xru Hey yo Database=db001 blah, blah, blah...

結果は次のようになります。

RandomSettings.xru someOtherWords Database=db001 blah, blah, blah...
MySettings.xru Lalala Database=db002 blah, blah, blah...
YourSettings.xru Hey yo Database=db001 blah, blah, blah...

ありがとう!

更新:自分で解決しました。

4

3 に答える 3

1

これが私の解決策です:

string[] filePaths = Directory.GetFiles(@"C:\test\", "*.config", SearchOption.AllDirectories);

int counter = 0;
string currentFile = string.Empty;
string currentLine = string.Empty;
string updatedLine = string.Empty;

foreach (string file in filePaths)
{
    currentFile = File.ReadAllText(file);

    if (currentFile.Contains("MySettings.xru"))
    {
        counter++;
        Debug.Print("Found in " + file);

        using (StreamReader streamReader = new StreamReader(file))
        {
            while (!streamReader.EndOfStream)
            {
                currentLine = streamReader.ReadLine();

                if (currentLine.Contains("MySettings.xru"))
                {
                    updatedLine = currentLine.Replace("db001", "db002");

                    break;
                }
            }
        }

        currentFile = currentFile.Replace(currentLine, updatedLine);

        // If file is ReadOnly then remove that attribute.
        FileAttributes attributes = File.GetAttributes(file);
        if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            File.SetAttributes(file, attributes ^ FileAttributes.ReadOnly);

        using (StreamWriter streamWriter = new StreamWriter(file))
        {
            streamWriter.Write(currentFile);
        }
    }
}
于 2012-08-23T15:33:02.443 に答える