44

ファイルtest.xmlの「how r u」などの文字列を、別のファイルxy.xml.using正規表現の文字列「i am fine」に置き換えたいです。

つまり、あるファイル (xy.xml) から文字列を読み取り、それを別のファイル test.xml に置き換える必要があります。そのため、この問題を解決するために必要な手順を例とともに提供してください

4

8 に答える 8

105

これはもう必要ありません...C# をプロジェクト/ビルド ファイルに挿入できるようになりました...

カスタム タスクとパラメータを次のように定義します。

<UsingTask TaskName="ReplaceFileText" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
  <ParameterGroup>
    <InputFilename ParameterType="System.String" Required="true" />
    <OutputFilename ParameterType="System.String" Required="true" />
    <MatchExpression ParameterType="System.String" Required="true" />
    <ReplacementText ParameterType="System.String" Required="true" />
  </ParameterGroup>
  <Task>
    <Reference Include="System.Core" />
    <Using Namespace="System" />
    <Using Namespace="System.IO" />
    <Using Namespace="System.Text.RegularExpressions" />
    <Code Type="Fragment" Language="cs">
      <![CDATA[
            File.WriteAllText(
                OutputFilename,
                Regex.Replace(File.ReadAllText(InputFilename), MatchExpression, ReplacementText)
                );
          ]]>
    </Code>
  </Task>
</UsingTask>

次に、他の MSBuild タスクと同じように呼び出すだけです

<Target Name="AfterBuild">
  <ReplaceFileText 
    InputFilename="$(OutputPath)File.exe.config" 
    OutputFilename="$(OutputPath)File.exe.config" 
    MatchExpression="\$version\$" 
    ReplacementText="1.0.0.2" />
</Target>

上記の例では、出力ディレクトリにある「File.exe.config」の「$version$」を「1.0.0.2」に置き換えます。

于 2014-03-22T00:01:14.453 に答える
4

編集:この回答は廃止されました。以下の解決策を使用してください...

ReadLinesFromFile タスクを使用して、xy.xml ファイルから置換文字列を取得します。これをチェックして

次に、xy.xml の値を FileUpdate タスクの置換文字列として使用します。これをチェックして

そして、それをすべてまとめてください;)

于 2011-10-25T11:36:16.883 に答える
4

記事http://geekswithblogs.net/mnf/archive/2009/07/03/msbuild-task-to-replace-content-in-text-files.aspxで説明されているように、MSBuild Community Tasks のタスク FileUpdate を使用できます。

于 2014-10-02T08:20:12.607 に答える
0

Unix ドライブにある同じファイルに対して両方の置換を実行し、\server\path... への unc パスを使用しました。

<ReplaceFileText
  InputFilename="$(fileToUpdate)"
  OutputFilename="$(fileToUpdate)"
  MatchExpression="15.0.0"
  ReplacementText="15.3.1"/>


<FileUpdate Files="$(fileToUpdate2)"
            Regex="15.0.0"
            ReplacementText="15.3.1" />

また、上記の cs カスタム アクションは bom を追加しません。ただし、FileUpdate は次のことを行いました。

%head -2 branding.h branding2.h
==> branding.h <==
#/* branding.h
#** This file captures common branding strings in a format usable by both sed and C-preprocessor.

==> branding2.h <==
#/* branding.h
#** This file captures common branding strings in a format usable by both sed and C-preprocessor.

csharptest.net に感謝します - UNIX ビルド用の perl 置換コマンドを使用して exec を実行していました。

于 2015-03-20T16:34:10.263 に答える