• 0

Printing across a network using C#


Question

Hi all

I am currently writing a service that will run once per day, retrieve data from a SQL database, and print some reports.

Here is the problem:

I have an xml config file which contains a report code (eg RPT001) and the printer it is to print to. This means that in future if I want to, I can simply change the printer name without too much disruption and the reports will be redirected elsewhere.

However, I am unable to set the printer name so that the report gets printed out. When I use :

// If we have specified a printer name print to this one otherwise the

// default printer will be used

if (_printerName != "")

{

pd.PrinterSettings.PrinterName = String.Format("{0}", _printerName);

}

A call to pd.PrinterSettings.IsValid, always returns false.

I have been looking into the PrintingPermissions topic, however I am unable to find a proper clear sample of how to use it so that I can grant access to my code to be able to print across the network.

The printers are connected to a central print server, however specifying "\\servername\printer" doesnt seem to work either.

To complete the picture, the code which performs the printing is in its own DLL and the service references this DLL.

What changes need to be made and where to get this to work?

Any and all help is very much appreciated :D

Link to comment
https://www.neowin.net/forum/topic/613622-printing-across-a-network-using-c/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

Hi,

Printing permissions work like so:

PrintingPermission perm = new PrintingPermission(System.Security.Permissions.PermissionState.Unrestricted);
perm.Level = PrintingPermissionLevel.AllPrinting;

Setting PrinterSettings.PrinterName should accept the sting network printer name, however, it might be easier to create a server side local printer that points to the network printer, and print to the local printer instead.

I haven't done much printing in .NET yet, but I will keep looking into it for you.

  • 0

Ahh thanks for the reply, but where do I put this code?

Does it go into my service, or into the printing DLL.

Ultimately the service I am writing will sit on a server somewhere and just poll every day, so I need it to be as hassle free as possible

  • 0

Thanks Antaris for your help.

I actually got it working without the code permissions part. Turned out the printer names had been renamed to all caps and that was throwing the code off.

So when I changed these in my config file it worked fine.

  • 0

Ok, I'm back again with a similar issue and this one has me stumped.

After running fine for months, I added a new printer name to the xml file, in the same format ... \\server\printername

However, when the code runs normally, I get an error back saying the printer name is invalid:

// If we have specified a printer name print to this one otherwise the 
// default printer will be used
if (_printerName != "")
{
pd.PrinterSettings.PrinterName = String.Format("{0}", _printerName);
}


if (pd.PrinterSettings.IsValid != false)
{
			//  Print stuff here
}

However, when I step through the code in debug mode, IsValid becomes true and the reports print fine.

I figured it had something to do with how long it was taking me to step to the next line of code (some sort of network delay possibly on name resolution), so I added a Sleep statement on the current thread to see if that would fix it - no such luck.

I know the printer name is valid, as I can print to it when I step through the code in debug mode, however this has to be deployed and just work so this cant be an option.

Any ideas would be appreciated.

Thanks

  • 0

Yeah the versions are the exact same, the only thing that was different is the name of the printer being passed in.

I've actually now got this working:

1) Tried the source code on a colleagues machine ---> worked flawlessly, not a problem (!)

2) Removed the network printer from my machine (again) and it now works no problem (!)

So thats that little bit sorted out.

Now if only I could make the pages print properly in landscape mode, I'd be done.

I've tried setting

e.PageSettings.Landscape = true

in the PrintPage event handler, but it doesnt work the way I want it to.

Back to the drawing board. . . . . . . .

  • 0

Qwerky windows flaws eh?

  ramesees said:
Now if only I could make the pages print properly in landscape mode, I'd be done.

I've tried setting

e.PageSettings.Landscape = true

in the PrintPage event handler, but it doesnt work the way I want it to.

Back to the drawing board. . . . . . . .

You would have thought that would be the answer, but alas no, you have to apply that setting earlier:

public void DoPrint(string printerName) {
   PrintDocument document = new PrintDocument();
   document.PrinterSettings.PrinterName = printerName;
   document.DefaultPageSettings.Landscape = true;
   document.PrintPage += new PrintPageEventHandler(this.PrintPage);
   document.Print();
}

protected void PrintPage(object sender, PrintPageEventArgs e) {
   // do work
}

Hope that helps!

  • 0

Hi Antaris, thanks for your help, I tried that but that doesnt work either :(

I am working with custom written print code and I need to make it physically rotate the output on the page (like landscape, only every control and text box etc... has to be rotated by 90 degrees).

So its the mapping of one set of co-ordinates to another thats kind of got me a little stumped.

  • 0

Any gurus want to offer an explanation to this little doozey ?

I have some very simple test code to test whether or not the network printer I am printing to is valid or not (based on its name)

When I have it for printer 1 (example) I get True before and after I change the printer name

PrintDocument pd = new PrintDocument();

Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());
pd.PrinterSettings.PrinterName = @"\\printserver\printer1"
Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());

However when I have it for printer 2 (example) I get True before and False after I change the printer name.

Although when I delete printer 2 from Printers and Faxes and add it again, I get True, True, but any change to the printer preferences of this printer gives True, False again.

PrintDocument pd = new PrintDocument();

Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());
pd.PrinterSettings.PrinterName = @"\\printserver\printer2"
Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());

I am absolutely tearing my hair out over this now, and am about to throw it in the bin (figuratively of course).

Does anyone have any advice to offer me, network related, or hardware, or anything, it would be so much appreciated.

Thanks :D

By the way, printer 2 is a lexmark t644 printer, if that helps anything.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Windows 11 gets 1Password passkey integration, version 25H2, and more with the latest builds by Taras Buria Microsoft is finishing this week with a now typical build duo for the Dev and Beta Channel users. For Windows Insiders in the Dev Channel, Microsoft is rolling out build 26200.5670; for those in the Beta Channel, Microsoft prepared build 26120.4520. Both updates have nearly identical changelogs with a new 1Password passkey integration, bug fixes, and more. Another important thing worth noting is that build 26200.5670 is the first officially confirmed Windows 11 version 25H2 build. 25H2 is this year's Windows 11 annual feature update, and it is now properly communicated in Settings > System > About and in the winver dialog. Note that the Beta build is still based on version 24H2. As for 1Password, customers who use this password manager can now enjoy a more seamless passkey experience. Windows Security will use passkeys stored in your 1Password and save new passkeys there as well. However, this change requires installing 1Password Beta for Windows 11. Here are other changes included in today's builds that are rolling out gradually: [Voice access] We are temporarily disabling support for Japanese to iron out a few more bugs. [Settings] In addition to the small changes that we made in the EEA region for default browsers via Settings > Apps > Default apps with Build 26200.5603, we’re also making this change: The new default browser will be pinned to the Taskbar and Start menu unless you choose not to pin it by clearing the checkboxes. [File Explorer] Fixed an issue which could cause File Explorer Home to crash (potentially also making File Explorer crash on launch, since Home is the default section for File Explorer). Fixed an issue which could cause the thumbnail for a pinned favorite in Home to disappear. [Start menu] Fixed an issue which was causing duplicate entries to appear when interacting with folders on the Start menu. Fixed an issue where the folder expand animation wasn’t correct in some cases. [Input] Fixed a high hitting ctfmon.exe crash in the latest flights, which could impact the ability to type. [Other] Fixed a memory leak which could happen when lock screen was set to use a slide show, which could impact performance and reliability over time. Did some more work improving how dialogs in the system react to increased text scaling, for example the “You must restart your computer to apply these changes” dialog should now support it. Here are the fixes that are available to all: [General] Fixed the issue causing the Windows Vista boot sound to play instead of the Windows 11 boot sound. Unfortunately the fix wasn’t completely working in the last Dev Channel flight. [File Explorer] Fixed the issue causing File Explorer to not persist view changes after the last Dev Channel flight, including desktop icons. And here is the list of known issues: [General] [UPDATED!]When joining the Dev Channel on Windows 11, version 24H2 – you will no longer be offered Build 26200.5641 first and will be offered the most current update available in the Dev Channel. [UPDATED!] When joining the Beta Channel on Windows 11, version 24H2 – you no longer will be offered Build 26120.4250 first and will be offered the most current update available in the Beta Channel. [UPDATED!] Some Windows Insiders may experience a rollback trying to install this update with a 0x80070005 in Windows Update. We’re working on a fix for Windows Insiders impacted. If you are impacted, using Settings > System > Recovery > “Fix issues using Windows Update” may resolve the issue. [Start menu] The following are known issues for Windows Insiders with the new Start menu: Using touch to navigate the new Start menu may not work reliably. For example, it currently does not support the swipe-up gesture. Drag and drop capabilities are limited from “All” to “Pinned.” [Xbox Controllers] Some Insiders are experiencing an issue where using their Xbox Controller via Bluetooth is causing their PC to bugcheck. Here is how to resolve the issue. Open Device Manager by searching for it via the search box on your taskbar. Once Device Manager is open, click on “View” and then “Devices by Driver”. Find the driver named “oemXXX.inf (XboxGameControllerDriver.inf)” where the “XXX” will be a specific number on your PC. Right-click on that driver and click “Uninstall”. [Click to Do (Preview)] The following known issues will be fixed in future updates to Windows Insiders: Windows Insiders on AMD or Intel™-powered Copilot+ PCs may experience long wait times on the first attempt to perform intelligent text actions in Click to Do after a new build or model update. [File Explorer] The following are known issues for AI actions in File Explorer: Narrator scan mode may not work properly in the action result canvas window for the Summarize AI action for Microsoft 365 files when reading bulleted lists. As a workaround, you can use Caps + Right key to navigate. [Widgets] Until we complete support for pinning in the new widgets board experience, pinning reverts you back to the previous experience. You can find the complete changelog for the Dev build here and for the Beta build here.
    • I'm in agreement with you here. I think the Windows Snipping Tool has the easiest highlight functionality to use. You literally select the highlighter and then just highlight. All other editors I have tried require some bizarre set of steps. So, 2 thumbs up'n'd'aya! for the Windows Snipping Tool with Idiot Proof Highlighter!
    • Microsoft officially confirms that Windows 11 version 25H2 is coming later this year by Usama Jawad Microsoft released Dev and Beta builds for Windows 11 today, and while the updates contain nearly identical change logs, one interesting observation is confirmation that Dev Channel users will be seeing Windows 11, version 25H2 in Settings > System > About and winver moving forward. Even though we had heard some whispers about it before, this is the first time that Microsoft has officially confirmed this next feature update to Windows 11. In a much more detailed blog post, Microsoft has made recommendations to organizations about how they can prepare for the arrival of Windows 11, version 25H2. The Redmond tech firm has highlighted that version 24H2 and version 25H2 both share the same Windows servicing branch, which means that the upgrade process should be fairly quick due to the presence of enablement packages (eKB). For those who don't know, enablement packages are bits and pieces of disabled code containing new features that are activated by Microsoft during a feature upgrade. This means that Windows 11, version 24H2 PCs can quickly update to version 25H2 in a single restart since the new code is already there, it just needs to be toggled on. That said, if you are utilizing a PC older than version 24H2, you won't be too happy to hear that it doesn't share the same servicing branch as version 25H2. What this means is that you'll have to go through the regular upgrade process through Windows Update or Windows Autopatch, which can be notably longer and require multiple restarts. As always, Enterprise versions of Windows 11, version 25H2 will receive 36 months of support starting from the release date, while Pro and Home variants will enjoy 24 months of support. It is worth keeping in mind that while Microsoft has confirmed that Windows 11, version 25H2 will begin rolling out later this year, it hasn't confirmed a concrete release date yet.
    • Mozilla fixes Firefox crashes on Windows by Taras Buria Mozilla is rolling out yet another update for the Firefox browser. Version 140.0.2 follows the just-released version 140.0.1 to address more bugs causing crashes on Windows in certain scenarios. Here is what the release notes say: Fixed a startup crash on Windows experienced by some users. (Bug 1974259) According to a post on Bugzilla, Mozilla's bug tracker for Firefox, the browser crashes with the ERROR_INVALID_HANDLE or ERROR_INVALID_PARAMETER error. This happens when Exploit Protection is enabled in Windows security settings. While that is a feature a regular user is unlikely to fiddle with, Exploit Protection is enabled for apps from the Microsoft Store. As such, crashes are most likely occurring for users with Firefox downloaded from the Microsoft Store. Still, if Exploit Protection is enabled globally, "standard" Firefox downloaded from the official website also fails. Note that the bug does not affect newer Firefox versions. Now, with Firefox 140.0.2 out, the browser should no longer crash regardless of your security settings or the browser origin. For reference, you can find the release notes for the latest update here; for version 140.0.1 (which fixed a couple of crash-inducing bugs), here; and for version 140.0 (a major release), here. As usual, you can update Firefox by heading to Menu > Help > About Firefox. The browser is available on the official website, in the Microsoft Store for Windows 10 and 11 users, or on Neowin's Software page.
  • Recent Achievements

    • Week One Done
      emptyother earned a badge
      Week One Done
    • Week One Done
      DarkWun earned a badge
      Week One Done
    • Very Popular
      valkyr09 earned a badge
      Very Popular
    • Week One Done
      suprememobiles earned a badge
      Week One Done
    • Week One Done
      Marites earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      566
    2. 2
      ATLien_0
      180
    3. 3
      +FloatingFatMan
      172
    4. 4
      Xenon
      122
    5. 5
      Som
      112
  • Tell a friend

    Love Neowin? Tell a friend!