2015-11-19 34 views
1

如何重寫文本文件(在指定位置)並鎖定他?重寫文本文件

重寫它需要讀取然後寫入。 - 這很簡單 - 但我需要在整個重寫過程中將文件鎖定到所有其他進程。

我有方法。

public bool AccessBridge() 
    { 
     try 
     { 
      fs = new FileStream("bridge.ini", FileMode.Open, FileAccess.ReadWrite); 
      sr = new StreamReader(fs); 
      sw = new StreamWriter(fs); 
      return true; 
     } 
     catch (IOException ioe) 
     { 
      return false; 
     } 
    } 

然後另一個測試部分:

 string precteno = sr.ReadToEnd(); 
     //Some modify string 
     //now I need delete whole text from file 
     sw.Write(precteno); 

任何想法?我已經處理了第二天晚上。

回答

0

自己流的想法後,我拆卸的FileStream和發現的getter/setter位置。

解決方案:

string precteno = sr.ReadToEnd(); 
    precteno = stringModificator(precteno); 
    fs.Position = 3; 
    sw.Write(precteno); 
0

只需使用FileShare.None以獨佔方式打開它:

fs = new FileStream("bridge.ini", FileMode.Open, FileAccess.ReadWrite, FileShare.None); 

順便說一句......如果我是你,我就換那部分using

using (var fs = new FileStream("bridge.ini", FileMode.Open, FileAccess.ReadWrite, FileShare.None)) 
{ 
} 

這樣,流妥善處置。目前,我沒有在代碼中看到關閉流的任何地方(也許你在別的地方做它,因爲你已經聲明你的流不在這個方法中,但是是的)。

+0

這的確是一個很好的做法但沒有解決問題。如何使用相同的流清除文件? –

+0

@IgorQuirino解決什麼問題?問題在於鎖定文件。那個代碼沒有做到嗎? –

+0

在整個重寫過程中鎖定文件。開放流自己鎖定它。沒有實現來重寫,所以我需要閱讀它然後寫它 - 這是一個問題。所以問題是:如何使用相同的流清除文件? –

0

試試這個:

public bool AccessBridge() 
{ 
    try 
    { 
     fs = new FileStream("bridge.ini", FileMode.Open, FileAccess.ReadWrite); 
     sr = new StreamReader(fs); 
     string text = sr.ReadToEnd(); 
     //do text modifications 
     //... 
     sw = new StreamWriter(fs, false); 
     sw. Write(text) ; 
     return true; 

    } 
    catch (IOException ioe) 
    { 
     return false; 
    } 
} 
+0

它不工作,因爲它沒有constructior。 (只用字符串路徑工作) –