如果被中断,C#Console.Out()不会写入

时间:2012-11-02 05:20:16

标签: c# console-application filewriter

using System;
using System.Diagnostics;
using System.Collections;
using System.Management;
using System.IO;

FileStream ostrm;
    StreamWriter writer;
    TextWriter oldOut = Console.Out;
    try
    {
        ostrm = new FileStream ("./Output.txt", FileMode.OpenOrCreate, FileAccess.Write);
        writer = new StreamWriter (ostrm);
    }
    catch (Exception e)
    {
        Console.WriteLine("Cannot open Output for writing");
        Console.WriteLine(e.Message);
        return;
    }
    foreach (ManagementObject envVar in searcher.Get())
    {
        Console.WriteLine("Username: {0}", envVar["Name"]);
    }
    Console.SetOut (writer);
    foreach (ManagementObject envVar in searcher.Get())
    {
        Console.WriteLine("Username: {0}", envVar["Name"]);
    }
    Console.SetOut (oldOut);
    writer.Close();
    ostrm.Close();
Console.WriteLine("" +
Environment.NewLine + "Press any key to exit");
Console.ReadLine();

我在控制台应用程序中有这个代码,需要AGES来完成编写网络上的所有用户,如果它在任何阶段被中断,则Output.txt结束为空。有没有办法让它定期保存,以便如果发生任何事情我在文本文件中有用户名?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您是否尝试过Console.Out.Flush();

答案 1 :(得分:0)

该计划似乎两次做同样的工作。另外,不要重定向Console.Out尝试使用File.AppendAllText,如下所示:

foreach (ManagementObject envVar in searcher.Get()) {
    string str = string.Format("Username: {0}\r\n", envVar["Name"]);
    File.AppendAllText("./Output.txt", str);
}

AppendAllText将在每次写入时打开和关闭文件,因此它可能更慢但更可靠。