c# - 创建一个将写入文件或写入控制台输出的通用方法

标签 c# file-io console.writeline

我有两个主体相同的函数,一个写入文件,一个写入控制台。
有没有办法使文件/控制台与我传递给函数的内容通用?

public void WatchWindow()
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
            if (rowIndex < _colLengths[colIndex])
                Console.Write("{0} ", _actualWindow[colIndex]rowIndex].SymbolName);
            else
                Console.Write("   ");
         }
         Console.WriteLine();
     }
     Console.WriteLine();
}

public void PrintWindow(StreamWriter file)
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
             if (rowIndex < _colLengths[colIndex])
                 file.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName);
             else
                 file.Write("   ");
         }
         file.WriteLine();
     }
     file.WriteLine();
}

最佳答案

StreamWriter 是一个 TextWriterConsoleWrite* 静态方法写入 Console.OutConsole.Out 是一个TextWriter。所以常见的“东西”是在 TextWriter 上书写。

public void WriteToFile(StreamWriter file)
{
    PrintWindow(file);
}

public void WriteToConsole()
{
    PrintWindow(Console.Out);
}

public void PrintWindow(TextWriter writer)
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
            if (rowIndex < _colLengths[colIndex])
                writer.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName);
            else
                writer.Write("   ");
        }
        writer.WriteLine();
    }
    writer.WriteLine();
}

您可以使用 WriteToFile/WriteToConsole 方法(或直接使用 PrintWindow 方法,我将其重命名为更合适的名称,例如 WriteToTextWriter)

关于c# - 创建一个将写入文件或写入控制台输出的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946648/

相关文章:

c# - System.IO.Abstractions 用法

android - 从 res/raw 读取文件 .txt 并将其显示到 ListView 中

c# - 导致无法识别的转义C#的ASCII艺术

c# - ReadLine() 关闭我的控制台

c# - 在 C# 中快速加载/读取 TIFF 文件

c# - 如何在 PowerShell 中创建一个 Outlook 规则,将电子邮件无错误地移动到文件夹,使用在 C# 中完美运行的相同代码?

c - 在 C 中,我想以某种方式从文件中逐行读取文件的末尾长度发生变化

c# - 将 Console.WriteLine() 重定向到文本框

c# - 按 Bars 数选择最受欢迎的 Foo

c# - 更改默认字体的 AutoScaleMode 问题