2012-08-06 44 views
0

我有一段代码,我正在修改文件的内容。我实际上需要用一个新行替换文件中的一行。为此,我要这么做:String.Replace()擦除整个字符串-C#

private void btn_edit_Click(object sender, EventArgs e) 
    { 
     bufferedListView1.Items.Clear(); 
     StreamReader sr1 = new StreamReader("C:\\sample.txt"); 
     string file= sr1.ReadToEnd(); 
     if (file.Contains(pname + "@" + pno)) 
     { 
      file.Replace(pname + "@" + pno, txt_editname.Text+"@"+txt_editno.Text);//Results null in file 
     } 
     string efile= sr1.ReadToEnd(); // returns null 
     sr1.Close(); 
     StreamWriter sw1 = new StreamWriter("C:\\sample.txt"); 
     sw1.Write(efile); 
     sw1.Close(); 
     //Rest of the code 

pname, pno contains old values. txt_editname,txt_editno contains new values

我最终文件sample.txt的具有没有内容。是什么原因?

回答

5

不,您的电话file.Replace正在做绝对没有用 - 您没有使用返回值。

字符串在.NET中是不可变的,所以像Replace这样的方法不会更改现有字符串,它们会创建一个新字符串并返回对其的引用。你想:

file = file.Replace(pname + "@" + pno, ...); 

而作为这不会做任何事情时,搜索字符串是不是在文本中,你可以这样做无条件。

下一个的问题是,你这样做是:

string file= sr1.ReadToEnd(); 
... // code which doesn't change sr1 ... 
string efile= sr1.ReadToEnd(); // returns null 

实际上并不是返回空 - 它返回一个空字符串......因为你仍然来自同一StreamReader读取你已经读完了。你为什么这样做?

注意,你甚至不使用变量file你叫Replace后。

此外,您的代码缺少using语句,因此如果抛出异常,您将泄漏文件句柄(直到终结器清除它们)。你能避免这一切很容易,但 - 我怀疑这会做你想要什么:

private void btn_edit_Click(object sender, EventArgs e) 
{ 
    bufferedListView1.Items.Clear(); 
    string fileContents = File.ReadAllText("C:\\sample.txt"); 
    string replacedContents = fileContenxt.Replace(pname + "@" + pno, 
     txt_editname.Text + "@" + txt_editno.Text); 
    File.WriteAllText("C:\\sample.txt", replacedContents); 
    // Rest of code 
} 

还要注意的是,如果这是在WPF或WinForms应用程序,你真的不应该在做这一切IO一个UI线程...

+0

:感谢所有的信息。让我知道为什么我不应该做这一切都在UI线程? – Cdeez 2012-08-06 07:01:47

+1

因为如果你有一个长时间运行的操作(例如你的文件有一个巨大的文本),你的UI在操作运行时不会响应。所以用户会认为你的应用程序正在挂起。 – Andre 2012-08-06 07:07:46

1
file.Replace(pname + "@" + pno, txt_editname.Text+"@"+txt_editno.Text);//Results null in file 

返回一个字符串,您必须将其重新分配给文件。

file = file.Replace(pname + "@" + pno, txt_editname.Text+"@"+txt_editno.Text);//Results null in file 
0

正常的,你这样做

string efile= sr1.ReadToEnd(); // returns null 
... 
sw1.Write(efile); 
相关问题