2013-01-22 3 views
1

Почему код ниже не работает?String.Replace не работает с файлом php?

 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 не изменяются, я также попытался скопировать/вставить эти значения, чтобы убедиться, что они одинаковы. Но код всегда не работает

ответ

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).

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); 
Смежные вопросы