I used following code to print a pdf :
var fileName = filepath;
ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Arguments = ConfigurationManager.AppSettings["printer_name"];
psInfo.FileName = fileName;
psInfo.WindowStyle = ProcessWindowStyle.Hidden;
psInfo.Verb = "print";
psInfo.CreateNoWindow = false;
psInfo.UseShellExecute = true;
process = Process.Start(psInfo);
following to get status of printer :
string query = string.Format("SELECT * from Win32_Printer "+ "WHERE Name LIKE '% {0}'",printerName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Logger.LogInfo(""+property.Name, "" +property.Value);
}
}
and also tried following to monitor Print queue :
LocalPrintServer server = new LocalPrintServer();
PrintQueueCollection queueCollection = server.GetPrintQueues();
PrintQueue printQueue = null;
foreach (PrintQueue pq in queueCollection)
{
if (pq.FullName == "HP LaserJet P1505n")
printQueue = pq;
}
int numberOfJobs = 0;
if (printQueue != null)
numberOfJobs = printQueue.NumberOfJobs;
All i want to do is to know is wether the document i did print using (1) is printed succesfully or not!! (2)nd code Snippet just shows same property anme and values always.So cannot notify print status.(3)rd code Snippet always monitors queue once and says '0' numberofjobs.
So what is the actual way to getback the print status?
To Know about print job status..! Try this,
SelectQuery qry = new SelectQuery("PrintJob");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(qry))
using (ManagementObjectCollection printJobs = searcher.Get())
foreach (ManagementObject printJob in printJobs)
{
string name = (string) product["Name"];
string[] nameParts = name.Split(',');
string printerName = nameParts[0];
string jobNumber = nameParts[1];
string document = (string) product["Document"];
string jobStatus = (string) product["JobStatus"];
}
I hope this helps.
Related
I am not a C# programer but I need to format drive with 32KB cluster using C#. I found "Format method of the Win32_Volume class" but when I am trying to format drive I always get an error 15 (Cluster size is too small). This is my code:
public static int DriveFormatting(string driveLetter)
{
string FileSystem = "FAT32", Label = "";
Boolean QuickFormat = true, EnableCompression = false;
UInt32 ClusterSize = 32;
int result = -1;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume WHERE DriveLetter = '"+ driveLetter +"'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject management in searcher.Get())
{
Console.WriteLine("Formating disk " + driveLetter + "...");
result = Convert.ToInt32(management.InvokeMethod("Format", new object[] { FileSystem, QuickFormat, ClusterSize, Label, EnableCompression }));
}
return result;
}
How can I do this? Thanks in advance.
I'm about to create a tool which gets some system information.
Only the Lenovo BIOS (WakeOnLAN) request isn't doing what I want.
The debugger always stops with a "invalid request" error message.
I tried the following...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi", "SELECT * FROM Lenovo_BiosSetting WHERE InstanceName='ACPI\\PNP0C14\\1_0'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting.InstanceName='ACPI\\PNP0C14\\1_0'");
Code:
//LenovoWOL
public string GetLenovoWOL()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting", "SELECT * FROM ACPI\\PNP0C14\\1_0");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return Environment.NewLine + wmi.GetPropertyValue("CurrentSetting").ToString();
}
catch { }
}
return "Unknown";
}
Only if I remove the InstanceName part, the code works.
Could someone if you tell me, what I'm doing wrong.
Thanks for your help
Adrian
I found a solution.
Here my code. It's not pretty but it works.
ManagementPath path = new ManagementPath()
{
NamespacePath = #"root\wmi",
Server = textBox1.Text
};
ManagementScope scope = new ManagementScope(path);
SelectQuery Sq = new SelectQuery("Lenovo_BiosSetting");
ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher(scope, Sq);
ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
foreach (ManagementObject MO in osDetailsCollection)
{
if (MO["CurrentSetting"].ToString().Contains("WakeOnLAN"))
{
string[] arr = new string[3];
ListViewItem itm;
//add items to ListView
arr[0] = "";
arr[1] = "WakeOnLAN";
arr[2] = MO["CurrentSetting"].ToString();
itm = new ListViewItem(arr);
listView200.Items.Add(itm);
}
}
Adrian
at my work, we install printers on the per user basis. I'm trying to write a backup program that would list all networked printers given a username. Is that at all possible ? via WMI or System.IO would be OK. Here is the code that lists all the machines networked printers but not per user.
private void Button_Click(object sender, EventArgs e)
{
ConnectionOptions objConnection = new ConnectionOptions();
objConnection.Impersonation = ImpersonationLevel.Impersonate;
objConnection.EnablePrivileges = true;
string backupselectedcomputer = "Some Computer Name"
ManagementScope objScope = new ManagementScope("\\\\" + backupselectedcomputer +"\\root\\cimv2",objConnection);
objScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer Where Local = FALSE";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC)
{
//lbBackupprinters is a list box
lbBackupprinters.Items.Add(mo["Name"].ToString().ToUpper());
}
}
Figured out a way. Here is the code for anyone that comes across this issue.
private void ddlBackupselectuser_SelectionChangeCommitted(object sender, EventArgs e)
{
lbBackupprinters.Items.Clear();
string selecteduser = ddlBackupselectuser.Text;
string computer = ddlBackupselectcomp.Text;
string sid;
lblBackuppwd.Visible = true;
txtBackuppwd.Visible = true;
cboBackuppwdshow.Visible = true;
//BEGIN GRAB PRINTERS FROM REGISTRY
try
{
NTAccount ntuser = new NTAccount(selecteduser);
SecurityIdentifier sID = (SecurityIdentifier)ntuser.Translate(typeof(SecurityIdentifier));
lblBackupStatus.Text = sID.ToString();
sid = sID.ToString();
}
catch (IdentityNotMappedException)
{
lblBackupStatus.Text = "ERROR "+ ddlBackupselectuser.Text.ToString() + " contains no profile information";
lbBackupprinters.Items.Add("No Printers Found");
return;
}
ConnectionOptions co = new ConnectionOptions();
co.EnablePrivileges = true;
co.Impersonation = ImpersonationLevel.Impersonate;
System.Net.IPHostEntry h = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
string IPAddress = h.AddressList.GetValue(0).ToString();
string lm = System.Net.Dns.GetHostName().ToString();
try
{
ManagementScope myScope = new ManagementScope("\\\\" + computer + "\\root\\default", co);
ManagementPath mypath = new ManagementPath("StdRegProv");
ManagementClass wmiRegistry = new ManagementClass(myScope, mypath, null);
const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
//ManagementClass wmiRegistry = new ManagementClass("root/default",
//"StdRegProv",null);
string keyPath = #"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider\\" + sid + "\\Printers\\Connections";
object[] methodArgs = new object[] { HKEY_LOCAL_MACHINE, keyPath, null };
uint returnValue = (uint)wmiRegistry.InvokeMethod("EnumKey", methodArgs);
if (null != methodArgs[2])
{
string[] subKeys = methodArgs[2] as String[];
if (subKeys == null)
{
lbBackupprinters.Items.Add("No Printers Found");
return;
}
ManagementBaseObject inParam = wmiRegistry.GetMethodParameters("GetStringValue");
inParam["hDefKey"] = HKEY_LOCAL_MACHINE;
string keyName = "";
foreach (string subKey in subKeys)
{
//Display application name
keyPath = #"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider\\" + sid + "\\Printers\\Connections" + subKey;
keyName = "DisplayName";
inParam["sSubKeyName"] = keyPath;
inParam["sValueName"] = keyName;
ManagementBaseObject outParam = wmiRegistry.InvokeMethod("GetStringValue", inParam, null);
lbBackupprinters.Items.Add(subKey);
}
}
else
{
lbBackupprinters.Items.Add("No Printers Found");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
Here is how I print my flowdocument:
PrintDialog pd = new PrintDialog();
LocalPrintServer local = new LocalPrintServer();
PrintQueue pq = local.DefaultPrintQueue;//GetPrintQueue("[Printer Name]"); //e.g. local.GetPrintQueue("Microsoft XPS Document Writer");
pd.PrintQueue = pq;
PrintTicket pt = pq.DefaultPrintTicket;
pt.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA5);// or we can specify the custom size(width, height) here
pd.PrintTicket = pt;
pt.PageBorderless = PageBorderless.Borderless;
pt.PageOrientation = PageOrientation.ReversePortrait;
PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
double sizeWidth = capabilities.PageImageableArea.ExtentWidth;
double sizeHeight = capabilities.PageImageableArea.ExtentHeight;
var fd = new FlowDocument();
DocumentPaginator sd = ((IDocumentPaginatorSource)fd).DocumentPaginator;
sd.PageSize = new Size(sizeWidth + 20, sizeHeight);
pd.PrintDocument(sd, "My Doc");
// GET THE PRINTER STATUS IN MESSAGE BOX HERE..
MessageBox.Show(printerStatus()); // printerStatus() is a pseudo method to retrieve the status of the printer.
How can i get the current status of the printer so that it will output, Printing, Out of Paper, Paper jam, Printer Offline, etc message????
Upon searching, I came across this page: http://msdn.microsoft.com/en-us/library/system.printing.printqueuestatus.aspx
However I have no clue on it's usage. Can you any body help me to get in with it?
This print process is being running in a STA thread.
you can check like this
using System.Management;
class PrinterOffline
{
private static void Main(string[] args)
{
// Set management scope
ManagementScope scope = new ManagementScope("\\root\\cimv2");
scope.Connect();
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer("Name").ToString().ToLower();
if (printerName.Equals("Name_Of_Printer"))
{
Console.WriteLine("Printer = " + printer("Name"));
if (printer("WorkOffline").ToString().ToLower().Equals("true"))
{
// printer is offline by user
Console.WriteLine("Your Plug-N-Play printer is not connected.");
}
else
{
// printer is not offline
Console.WriteLine("Your Plug-N-Play printer is connected.");
}
}
}
}
}
pls go through this link for more information on status of the printer
I'm trying to get a list of all shared folders available on a local intranet server.
The System.IO.Directory.GetDirectories() works fine for a path like \\myServer\myShare, however I'm getting an exception for a path like \\myServer:
Unhandled Exception: System.ArgumentException: The UNC path should be of the form \server\share.
Is there a way to get a list all shared folders for a server? Ultimately I'm looking for a method that can handle both scenarios based on a given path - returning a list of all shares for a given server and returning a list of all subdirectories for a given network shared folder.
Here's a technique that uses System.Management (add a reference to this assembly):
using (ManagementClass shares = new ManagementClass(#"\\NameOfTheRemoteComputer\root\cimv2", "Win32_Share", new ObjectGetOptions())) {
foreach (ManagementObject share in shares.GetInstances()) {
Console.WriteLine(share["Name"]);
}
}
Appropriate permissions are required.
I think this is what you are looking for http://www.codeproject.com/KB/IP/networkshares.aspx
private DataTable GetSharedFolderAccessRule()
{
DataTable DT = new DataTable();
try
{
DT.Columns.Add("ShareName");
DT.Columns.Add("Caption");
DT.Columns.Add("Path");
DT.Columns.Add("Domain");
DT.Columns.Add("User");
DT.Columns.Add("AccessMask");
DT.Columns.Add("AceType");
ManagementScope Scope = new ManagementScope(#"\\.\root\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection QueryCollection = Searcher.Get();
foreach (ManagementObject SharedFolder in QueryCollection)
{
{
String ShareName = (String) SharedFolder["Name"];
String Caption = (String)SharedFolder["Caption"];
String LocalPath = String.Empty;
ManagementObjectSearcher Win32Share = new ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" + ShareName + "'");
foreach (ManagementObject ShareData in Win32Share.Get())
{
LocalPath = (String) ShareData["Path"];
}
ManagementBaseObject Method = SharedFolder.InvokeMethod("GetSecurityDescriptor", null, new InvokeMethodOptions());
ManagementBaseObject Descriptor = (ManagementBaseObject)Method["Descriptor"];
ManagementBaseObject[] DACL = (ManagementBaseObject[])Descriptor["DACL"];
foreach (ManagementBaseObject ACE in DACL)
{
ManagementBaseObject Trustee = (ManagementBaseObject)ACE["Trustee"];
// Full Access = 2032127, Modify = 1245631, Read Write = 118009, Read Only = 1179817
DataRow Row = DT.NewRow();
Row["ShareName"] = ShareName;
Row["Caption"] = Caption;
Row["Path"] = LocalPath;
Row["Domain"] = (String) Trustee["Domain"];
Row["User"] = (String) Trustee["Name"];
Row["AccessMask"] = (UInt32) ACE["AccessMask"];
Row["AceType"] = (UInt32) ACE["AceType"];
DT.Rows.Add(Row);
DT.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
return DT;
}