2011-04-13 36 views
1

我有第三方應用程序,它定期從我的C#.Net應用程序讀取輸出。
由於某些限制,我只能將輸出寫入文件,然後由第三方應用程序讀取。c#保持文件打開但覆蓋內容

我需要每次覆蓋同一個文件的內容。
我目前做的在C#中使用

Loop 
{ 
    //do some work 
    File.WriteAllText(path,Text); 
} 

的第三方應用程序會定期檢查該文件並讀取內容。這工作得很好,但CPU使用率非常高。用文本編寫器代替File.WriteAllText解決了高CPU使用率的問題,但是我的文本被附加到文件而不是覆蓋文件。

難道有人指向我正確的方向,我可以保持文件在C#中打開,並定期覆蓋其內容,沒有太多的開銷?

編輯:我通過選擇每循環20次迭代寫入文件來修復CPU使用率,而不是每循環一次。下面給出的所有答案都有效,但是與關閉文件並重新打開有關。謝謝

回答

0

使用文本編寫器,但在開始寫入之前清除文件的內容。類似這樣的:

 string path = null;//path of file 
     byte[] bytes_to_write = null; 
     System.IO.File.WriteAllText(path, string.Empty); 
     System.IO.FileStream str = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Write, System.IO.FileShare.Read); 
     str.Write(bytes_to_write, 0, bytes_to_write.Length); 

也許這個例子中的某些東西會有所幫助?

+0

清零使用 System.IO.File.WriteAllText(路徑,的String.Empty)我的循環每一次的文件; 也將導致相同的開銷,因爲我將不得不在循環中重複執行。 – newidforu 2011-04-13 18:39:53

3

使用File.OpenFileModeTruncate爲您的TextWriter創建文件流。

1

有人能指出我在正確的方向,我可以保持一個文件在C#開放,並定期覆蓋其內容沒有太多的開銷?

下面是我在Silverlight 4中做到的。既然您沒有使用Silverlight,您將不會使用獨立存儲,但是無論支持存儲如何,相同的技術都可以工作。

感興趣的是在Write()方法:

logWriter.BaseStream.SetLength(0); 

Stream.SetLength方法:

在派生類中重寫,設置當前流的長度。

一定要衝洗使用任一自動沖洗流(如我在這個例子中那樣),或者由logWriter.Write()之後加入logWriter.Flush()

/// <summary> 
/// Represents a log file in isolated storage. 
/// </summary> 
public static class Log 
{ 
    private const string FileName = "TestLog.xml"; 
    private static IsolatedStorageFile isoStore; 
    private static IsolatedStorageFileStream logWriterFileStream; 
    private static StreamWriter logWriter; 

    public static XDocument Xml { get; private set; } 

    static Log() 
    { 
     isoStore = IsolatedStorageFile.GetUserStoreForApplication(); 
     logWriterFileStream = isoStore.OpenFile(
      FileName, 
      FileMode.Create, 
      FileAccess.Write, 
      FileShare.None); 
     logWriter = new StreamWriter(logWriterFileStream); 
     logWriter.AutoFlush = true; 

     Xml = new XDocument(new XElement("Tests")); 
    } 

    /// <summary> 
    /// Writes a snapshot of the test log XML to isolated storage. 
    /// </summary> 
    public static void Write(XElement testContextElement) 
    { 
     Xml.Root.Add(testContextElement); 
     logWriter.BaseStream.SetLength(0); 
     logWriter.Write(Xml.ToString()); 
    } 
}