How can I print a text file in C#? In a console application.

This is what I've found: msdn sample and this stackoverflow:answer is the msdn sample

The code from the links are for windows forms applications, and does'nt work in an console appliction.

Here is what I've found:

 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);

Since you say this question is off topic and not relevant here is a link to what I'm trying to learn: This is documentation of the .Net framework and this is why I'm asking the question, I'm trying to learn about the various uses of .Net classes.

1

Best Answer


You can use the PRINT verb to print a file to the default printer using the Process and ProcessStartInfo classes:

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\temp\output.txt");psi.Verb = "PRINT";Process.Start(psi);

If you want to make sure the file has been sent to printer before continuing, use Process.WaitForExit(). It may be required, for example, to prevent deletion of that file before it has been printed:

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 );}