简体   繁体   English

如何在Windows XP上成功关闭TextWriter流?

[英]How can I close the TextWriter stream on Windows XP successfully?

I have a code like the following one for working with a TextWriter stream. 我有一个类似以下代码的代码可用于处理TextWriter流。

TextWriter TR = new StreamWriter(@"")

try
{

    //Logic

}
catch (Exception exception)
{

    //Error Reporting

}
finally
{

    if (TR != null)
        TR.Close();

}

My .Net version is 4.0 and this code works properly on Windows 7 but it does not work properly in Windows XP!! 我的.Net版本是4.0,此代码在Windows 7上可以正常运行,但在Windows XP上则不能正常运行! It seems that the stream does not close and a number of buffers are not written to file! 似乎流没有关闭,并且许多缓冲区未写入文件! I have no idea! 我不知道! Can anyone help me to solve this problem please? 谁能帮我解决这个问题?

It sounds like the problem isn't that the streams haven't closed, but rather than the streams may have been closed before they have written. 听起来问题不是不是流没有关闭,而是流在写入之前就已经关闭了。 With most stream output you will need to Flush the output stream to ensure that the changes have been written before you Close it. 对于大多数流输出,您将需要在关闭流之前刷新输出流以确保已写入更改。 If you don't, then unflushed data will be lost, which sounds very much like what you're seeing. 如果您不这样做,那么未刷新的数据将丢失,这听起来很像您所看到的。

As Gerald suggested, I would also recommend the 正如杰拉尔德(Gerald)建议的那样,我还建议

using(var writer = new StreamWriter(@"")
{
    // ...

    writer.Flush();
} 

format, because while it just achieves much the same as try{...}finally{...} it is a little more elegant, and slightly easier to get right. 格式,因为虽然它最终获得的效果与try {...}最终{...}大致相同,但它更优雅一些,并且更容易正确使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用TextWriter时如何截断流 - How to truncate a stream when using a TextWriter Windows XP将屏幕淡化为灰色时,如何通知我? - How can I be notified when Windows XP fades the screen to gray? 如何在Xp中使用Windows Mobile Center? - How can I used Windows Mobile center in Xp? 如何在 C# 中获取 Windows XP 产品密钥? - How can I get windows XP product key in C#? 如何使用 C# 或免费的 XP 工具卸载或删除 Windows XP Sp3 游戏? - How can I uninstall or delete Windows XP Sp3 Games using C# or free XP tools? 我怎样才能自动关闭Excel Windows? - How I can close a excel windows automatic? 如何在Windows Server 2003和Windows XP中延迟创建的服务? - How can I delay my created service in Windows Server 2003 & Windows XP? 如何实现TextWriter以便将时间戳添加到写入控制台的每一行? - How can I implement a TextWriter in order to append a timestamp to each line writen to the console? 在Windows 7中成功计划和运行的任务无法在Windows XP中运行 - Task that successfully scheduled and ran in Windows 7 could not run in Windows XP 如果未在管理模式下运行,如何阻止我的程序运行? XP和Windows 7 - How can I prevent my program from running if it is not ran in Administrative mode? XP and Windows 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM