c# 保持文件打开但覆盖内容
我有一个第 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
File.Open
和FileMode
Truncate
为TextWriter
创建文件流。Use
File.Open
withFileMode
Truncate
to create the file stream for yourTextWriter
.以下是我在 Silverlight 4 中的做法。由于您没有使用 Silverlight,因此您不会使用独立存储,但无论后备存储如何,相同的技术都可以工作。
有趣的是 Write() 方法:
来自
Stream.SetLength
方法:请务必使用 AutoFlush(如我在本示例中所做的那样)或在
logWriter.Write()
之后添加logWriter.Flush()
来刷新流。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:
From
Stream.SetLength
Method:Be sure to flush the stream using either AutoFlush (as I did in this example), or by adding a
logWriter.Flush()
after thelogWriter.Write()
.使用文本编写器,但在开始写入之前清除文件的内容。像这样的事情:
也许这个例子中的一些东西会有帮助?
Use the text writer, but clear the contents of the file before you begin writing. Something like this:
Perhaps something from this example will help?
将
false
作为构造函数的append 参数
传递:参考:http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
Pass
false
as theappend parameter
of the constructor:Ref: http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
您尝试过使用 Thread.Sleep 吗?
http://msdn.microsoft.com/en-us /library/system.threading.thread.sleep.aspx
Have you tried using Thread.Sleep?
http://msdn.microsoft.com/en-us/library/system.threading.thread.sleep.aspx