String.Replace不能用于php文件?

时间:2013-01-22 11:29:40

标签: c# .net

为什么下面的代码不起作用?

      string Tmp_actionFilepath = @"Temp\myaction.php";


       // change the id and the secret code in the php file
            File.Copy(@"Temp\settings.php", Tmp_actionFilepath, true);
            string ActionFileContent = File.ReadAllText(Tmp_actionFilepath);
            string unique_user_id = textBox5.Text.Trim();
            string secret_code = textBox1.Text.Trim();
            ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
            ActionFileContent.Replace("SECRET_CODE", secret_code);
            File.WriteAllText(Tmp_actionFilepath, ActionFileContent);

以下是setting.php的内容

      <?php
      session_start();
      $_SESSION["postedData"] = $_POST;

      /////////////////////////////////////////////////////////
      $_SESSION["uid"] = "UNIQUE_USER_ID";
      $_SESSION["secret"] = "SECRET_CODE";
      /////////////////////////////////////////////////////////

      function findThis($get){
      $d = '';
      for($i = 0; $i < 30; $i++){
      if(file_exists($d.$get)){
        return $d;
      }else{
        $d.="../";
      }
    }
  }


   $rootDir = findThis("root.cmf");

   require_once($rootDir."validate_insert.php");

上面的代码有什么问题?在c#中编译代码之后,我注意到创建了myaction.php文件,但是值:UNIQUE_USER_ID和SECRET_CODE没有改变,我还尝试复制/粘贴这些值以确保它们是相同的。但代码总是不起作用

2 个答案:

答案 0 :(得分:5)

String.Replace返回一个新字符串,因为字符串是不可变的。它不会替换您调用它的字符串。

你应该替换:

ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);

使用:

ActionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent = ActionFileContent.Replace("SECRET_CODE", secret_code);

最重要的是,您应该更改变量名称,以便它们遵循常规的C#命名约定(即使用actionFileContent而不是ActionFileContent)。

答案 1 :(得分:2)

您必须在字符串上设置replace字符串方法的结果。

string Tmp_actionFilepath = @"Temp\myaction.php";

// change the id and the secret code in the php file
File.Copy(@"Temp\settings.php", Tmp_actionFilepath, true);

string actionFileContent = File.ReadAllText(Tmp_actionFilepath);

string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();

// set the result of the Replace method on the string.
actionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id)
                                     .Replace("SECRET_CODE", secret_code);

File.WriteAllText(Tmp_actionFilepath, actionFileContent);
相关问题