如何解决c#保持文件打开但覆盖内容
| 我有一个第三方应用程序,该应用程序会定期从C#.Net应用程序读取输出。由于某些限制,我只能将输出写入文件,然后由第三方应用程序读取该文件。 我每次都需要覆盖同一文件的内容。 我目前正在C#中通过使用Loop
{
//do some work
File.WriteAllText(path,Text);
}
第三方应用程序会定期检查文件并读取内容。这样效果很好,但CPU使用率却很高。用文本编写器替换File.WriteAllText解决了CPU使用率高的问题,但是我的文本被追加到文件中而不是覆盖文件。
有人可以指出正确的方向,使我可以在C#中打开文件并定期覆盖文件内容而不会产生太多开销吗?
编辑:我通过选择每20次循环而不是每次循环写入一次文件来固定CPU使用率。下面给出的所有答案都可以使用,但是与关闭文件并重新打开相关的开销。谢谢
解决方法
将
File.Open
与FileMode
Truncate
一起使用来为TextWriter
创建文件流。
, 有人可以指出正确的方向,使我可以在C#中打开文件并定期覆盖文件内容而不会产生太多开销吗?
这是我在Silverlight 4中所做的操作。由于您没有使用Silverlight,因此不会使用隔离存储,但是无论后备存储如何,相同的技术都可以使用。
有趣的是在Write()方法中:
logWriter.BaseStream.SetLength(0);
从Stream.SetLength
方法开始:
在派生类中重写时,设置当前流的长度。
确保使用自动冲洗(如本例中所做的那样)或在logWriter.Write()
之后添加ѭ7to冲洗流。
/// <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());
}
}
,使用文本编写器,但在开始编写之前清除文件的内容。像这样:
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,bytes_to_write.Length);
也许这个例子有帮助?
,将false
作为构造函数的append parameter
传递:
TextWriter tsw = new StreamWriter(path,false);
参考:http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
,您是否尝试过使用Thread.Sleep?
http://msdn.microsoft.com/zh-CN/library/system.threading.thread.sleep.aspx
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。