2010-06-08 56 views
0

我有用C#.NET編寫的windows服務。該服務在內部計時器上運行,每次間隔命中時,它都會去並嘗試將此日誌文件讀取到String中。文件被服務鎖定(服務代碼讀取文本文件後)

我的問題是每次讀取日誌文件時,服務似乎都會鎖定日誌文件。該日誌文件上的鎖定將繼續,直到我停止Windows服務。同時該服務正在檢查日誌文件,同一個日誌文件需要由另一個程序不斷更新。如果文件鎖定打開,另一個程序無法更新日誌文件。

這是我用來讀取文本日誌文件的代碼。

 private string ReadtextFile(string filename) 
    { 
     string res = ""; 
     try 
     { 
      System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); 
      System.IO.StreamReader sr = new System.IO.StreamReader(fs); 

      res = sr.ReadToEnd(); 

      sr.Close(); 
      fs.Close(); 
     } 
     catch (System.Exception ex) 
     { 
      HandleEx(ex); 
     } 

     return res; 
    } 

謝謝。

回答

2

我建議關閉該文件中Finally語句,以確保其得到執行

System.IO.FileStream fs = null; 
System.IO.StreamReader sr = null; 
try{ 
    fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); 
    sr = new System.IO.StreamReader(fs); 

    res = sr.ReadToEnd(); 
} 
catch (System.Exception ex) 
{ 
    HandleEx(ex); 
} 
finally 
{ 
    if (sr != null) sr.Close(); 
    if (fs != null) fs.Close(); 
} 

或者嘗試使用using聲明:

using (FileStream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read)) 
{ 
    ... 
} 
+1

+1爲'using'尖端。 – 2010-06-08 22:38:33

0

您需要使用四個參數形式的FileStream幷包括訪問掩碼FileShare.Read

var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); 

這種方式打開文件的方式允許多個併發讀取器。此外,編寫的代碼也需要用FileShare.Read將其打開。

+0

我認爲你應該使用FileShare.Write而不是閱讀(accordind to http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx) – munissor 2010-06-08 21:39:30

+0

我已經嘗試了4參數的形式,甚至與FileShare.Delete。它仍然不起作用。似乎服務將保持鎖定文件,直到服務停止。 – rvpals 2010-06-09 19:09:29

+0

@rvpals,你是否更新了寫入文件的代碼和讀取文件的代碼? – 2010-06-09 19:26:06

1

嘗試使用:

using (FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
{ 
    using(StreamReader sr = new System.IO.StreamReader(fs)) 
    { 
     res = sr.ReadToEnd(); 
    } 
} 
+0

試過了,仍然不起作用。謝謝 – rvpals 2010-06-09 19:21:09

+0

另一個程序是否釋放鎖?你在這個盒子上有反病毒嗎?它真的是鎖定文件的服務(使用進程管理器驗證)? – marapet 2010-06-09 19:40:30

+0

嗨,我使用ProcessExplorer找出是的,這是我的服務是持有的文件。 – rvpals 2010-06-09 20:13:23