1

我有一个第 3 方应用程序,它定期从我的 C#.Net 应用程序读取输出。
由于某些限制,我只能将输出写入文件,然后由第 3 方应用程序读取。

我每次都需要覆盖同一个文件的内容。
我目前正在 C# 中使用

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

3rd 方应用程序定期检查文件并读取内容。这很好用,但会使 CPU 使用率非常高。用文本编写器替换 File.WriteAllText 解决了 CPU 使用率高的问题,但随后我的文本被附加到文件而不是覆盖文件。

有人能指出我可以在 C# 中保持文件打开并定期覆盖其内容而没有太多开销的正确方向吗?

编辑:我通过选择每 20 次循环迭代而不是每次循环迭代写入文件来修复 CPU 使用率。下面给出的所有答案都有效,但会产生与关闭文件和重新打开相关的开销。谢谢

4

5 回答 5

3

使用File.OpenwithFileMode Truncate为您的TextWriter.

于 2011-04-13T18:37:24.280 回答
1

有人能指出我可以在 C# 中保持文件打开并定期覆盖其内容而没有太多开销的正确方向吗?

这是我在 Silverlight 4 中的做法。由于您没有使用 Silverlight,因此您不会使用隔离存储,但无论后备存储如何,相同的技术都可以使用。

有趣的是在 Write() 方法中:

logWriter.BaseStream.SetLength(0);

Stream.SetLength方法:

在派生类中重写时,设置当前流的长度。

请务必使用 AutoFlush(就像我在本例中所做的那样)或logWriter.Flush()logWriter.Write().

/// <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());
    }
}
于 2011-07-09T21:56:38.767 回答
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);

也许这个例子中的一些东西会有所帮助?

于 2011-04-13T18:37:09.167 回答
0

false作为append parameter构造函数的传递:

TextWriter tsw = new StreamWriter(path, false);

参考:http: //msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

于 2011-04-13T18:52:37.510 回答
0

您是否尝试过使用 Thread.Sleep?

http://msdn.microsoft.com/en-us/library/system.threading.thread.sleep.aspx

于 2011-04-13T21:44:54.070 回答