0
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 最终会是空的。有没有办法让它定期保存,以便如果发生任何事情我在文本文件中有用户名?

任何帮助是极大的赞赏。

4

2 回答 2

2

你试过Console.Out.Flush();吗?

于 2012-11-02T05:22:14.730 回答
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 将在每次写入时打开和关闭文件,因此它可能会更慢但更可靠。

于 2012-11-02T05:31:27.353 回答