2012-02-28 45 views
0

我正在写c#代码来替换文件中的某些单词。我写的2行演示简单代码不起作用。没有错误并且Console.WriteLine也正在给出正确的输出。为什么不是string.Replace按我的预期工作?

string strFileContent = File.ReadAllText(@"C:\Users\toshal\Documents\TCS\stop_words.txt"); 
Console.WriteLine("strfilecontent" + strFileContent); 
strFileContent = strFileContent.Replace("actually" , " "); 

字符串“实际”没有在文件中被替换。 这里有什么问题?

+1

这里有什么问题?此代码将在替换之前打印字符串,并且不会将字符串保存回文件。 – DaveShaw 2012-02-28 11:52:20

+1

你的意思是变量strFileContent在替换调用后没有改变,因为在你的例子中你不再使用它了吗? – 2012-02-28 11:52:48

+1

您需要将'strFileContent'字符串发送回该文件,该内容将在内存中被替换,但不会退出到该文件。 – dougajmcdonald 2012-02-28 11:53:02

回答

5

您正在创建一个替换值的字符串,但不会将该值写回文件。因此,该文件保持不变。

要修复,添加以下行来写更改值回文件:

string path = @"C:\Users\toshal\Documents\TCS\stop_words.txt"; 
string strFileContent = File.ReadAllText(path); 
Console.WriteLine("strfilecontent" + strFileContent); 
strFileContent = strFileContent.Replace("actually" , " "); 
File.WriteAllText(path, strFileContent); 
10

Ofcourse它没有得到文件中所取代,因为你只数据,然后改变它。

如果要应用更改,您必须将其写回文件。

string strFileContent = File.ReadAllText(@"C:\Users\toshal\Documents\TCS\stop_words.txt"); 
Console.WriteLine("strfilecontent" + strFileContent); 
strFileContent = strFileContent.Replace("actually" , " "); 

StreamWriter SW = File.CreateText(@"C:\Users\toshal\Documents\TCS\stop_words.txt"); 
SW.Write(strFileContent); 
SW.Close(); 
相关问题