简体   繁体   中英

Print file using c# windows service

I want to print files in a directory automatically using windows server. As soon as any file is added to the directory it should get automatically printed. How can we achieve this?

Thanks.

I haven't tested printing from another thread, but one of these two options should work. You might have to modify the code to work with .Net 2 since I only use 3.5 Sp1 or 4.

Assuming you have a Print method and a Queue where ItemToPrint is the class holding the print settings / information

public Queue<ItemToPrint> PrintQueue = new Queue<ItemToPrint>();
    private BackgroundWorker bgwPrintWatcher;

    public void SetupBackgroundWorker()
    {
        bgwPrintWatcher = new BackgroundWorker();
        bgwPrintWatcher.WorkerSupportsCancellation = true;
        bgwPrintWatcher.ProgressChanged += new ProgressChangedEventHandler(bgwPrintWatcher_ProgressChanged);
        bgwPrintWatcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwPrintWatcher_RunWorkerCompleted);
        bgwPrintWatcher.DoWork += new DoWorkEventHandler(bgwPrintWatcher_DoWork);
        bgwPrintWatcher.RunWorkerAsync();
    }

    void bgwPrintWatcher_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (!worker.CancellationPending)
        {
            // Prevent writing to queue while we are reading / editing it
            lock (PrintQueue)
            {
                if (PrintQueue.Count > 0)
                {
                    ItemToPrint item = PrintQueue.Dequeue();
                    // Two options here, you can either sent it back to the main thread to print
                    worker.ReportProgress(PrintQueue.Count + 1, item);
                    // or print from the background thread
                    Print(item);
                }
            }
        }
    }

    private void Print(ItemToPrint item)
    {
        // Print it here
    }

    private void AddItemToPrint(ItemToPrint item)
    {
        lock (PrintQueue)
        {
            PrintQueue.Enqueue(item);
        }
    }

    void bgwPrintWatcher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // Anything here will run from the main / original thread
        // PrintQueue will no longer be watched
    }

    void bgwPrintWatcher_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Anything here will run from the main / original thread
        ItemToPrint item = e.UserState as ItemToPrint;
        // e.ProgressPercentage holds the int value passed as the first param
        Print(item);
    }

You can use the FileSystemWatcher Class.

Description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM