2012-08-06 43 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); 
相關問題