如何使用C#打印文本文件

3

如何在C#中打印文本文件?在控制台应用程序中。

这是我找到的东西:msdn示例和这个stackoverflow:答案是msdn示例

以上链接中的代码适用于Windows窗体应用程序,在控制台应用程序中不起作用。

以下是我找到的:

    string fileName = @"C:\data\stuff.txt";
        ProcessStartInfo startInfo;
        startInfo = new ProcessStartInfo(fileName);

        if (File.Exists(fileName))
        {
            int i = 0;
            foreach (String verb in startInfo.Verbs)
            {
                // Display the possible verbs.
                Console.WriteLine("  {0}. {1}", i.ToString(), verb);
                i++;
            }
        }

        startInfo.Verb = "print";
        Process.Start(startInfo);

由于您说这个问题是不相关的,请看我正在尝试学习的链接:这是 .Net 框架的文档,这就是我提出这个问题的原因,我正在尝试了解 .Net 类的各种用途。


1
你写过任何代码吗?你尝试了什么?有出现任何错误吗? - Amicable
1
你做过谷歌搜索吗? - Micah Armantrout
3
您需要解释为什么那些链接对您无效。如果不解释,您的问题可能会被关闭为重复。 - Conrad Frix
该链接适用于WinForm而非控制台应用程序。 - Micah Armantrout
你可以在控制台应用程序中使用 System.Windows.WinForms... - germi
我对这段代码一无所知,我正在学习C#,并寻找代码以便理解和操作。我有很多关于C#的书籍,但想练习其他东西,因为阅读和编写代码有点让人感到无聊。我只是想要一些新鲜的样例来查看和理解,以完成一些特定任务,例如从我的程序中打印文档。 - somethingSomething
1个回答

13
你可以使用 ProcessProcessStartInfo 类,使用 PRINT 命令将文件打印到默认打印机:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\temp\output.txt");
psi.Verb = "PRINT";

Process.Start(psi);

如果您想确保文件已发送到打印机,然后再继续操作,请使用Process.WaitForExit()。例如,可能需要在文件被打印之前防止删除该文件。
static void PrintText( string text )
{   string           filegen, filetxt;
    ProcessStartInfo psi;
    Process          proc;

    filegen = Path.GetTempFileName();
    filetxt = filegen + ".txt";
    File.Move( filegen, filetxt );
    File.AppendAllText( filetxt, text  );

    psi = new ProcessStartInfo( filetxt );
    psi.Verb = "PRINT";
    proc = Process.Start( psi );
    proc.WaitForExit();
    File.Delete( filetxt );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接