c# 保持文件打开但覆盖内容

发布于 2024-10-31 22:39:53 字数 475 浏览 4 评论 0原文

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

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

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

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

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

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

I have a 3rd party application that periodically reads output from my C#.Net application.
Due to certain constraints, I can only write output to a file which then gets read by the 3rd party application.

I need to overwrite the contents of the same file each time.
I am currently doing it in C# by using

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

The 3rd party application periodically checks the file and reads the contents. This works well but pushes the CPU usage very high. Replacing File.WriteAllText with a text writer solves the issue of high CPU usage but then my text gets appended to the file instead of overwriting the file.

Could someone point me in the right direction where I can keep a file open in C# and periodically overwrite its contents without too much overhead?

Edit: I fixed the CPU usage by opting to write to the file once every 20 iterations of the loop instead of every iteration of the loop. All the answers given below work but have overhead associated with closing the file and reopening. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

帥小哥 2024-11-07 22:39:53

使用 File.OpenFileMode TruncateTextWriter 创建文件流。

Use File.Open with FileMode Truncate to create the file stream for your TextWriter.

記憶穿過時間隧道 2024-11-07 22:39:53

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

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

有趣的是 Write() 方法:

logWriter.BaseStream.SetLength(0);

来自 Stream.SetLength 方法:

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

请务必使用 AutoFlush(如我在本示例中所做的那样)或在 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());
    }
}

Could someone point me in the right direction where I can keep a file open in C# and periodically overwrite its contents without too much overhead?

Here is how I did it in Silverlight 4. Since you are not using Silverlight, you won't use isolated storage, but same technique will work regardless of the backing store.

The interesting bit is in the Write() method:

logWriter.BaseStream.SetLength(0);

From Stream.SetLength Method:

When overridden in a derived class, sets the length of the current stream.

Be sure to flush the stream using either AutoFlush (as I did in this example), or by adding a logWriter.Flush() after the 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());
    }
}
南城旧梦 2024-11-07 22:39:53

使用文本编写器,但在开始写入之前清除文件的内容。像这样的事情:

        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);

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

Use the text writer, but clear the contents of the file before you begin writing. Something like this:

        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);

Perhaps something from this example will help?

时光是把杀猪刀 2024-11-07 22:39:53

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

TextWriter tsw = new StreamWriter(path, false);

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

Pass false as the append parameter of the constructor:

TextWriter tsw = new StreamWriter(path, false);

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文