Search code examples
c#visual-studiofile-handlingzebra-printersfilehandle

How to close all file handles on the file and delete it, which is being copied and given to printer for printing job


I have a C# application in which i am sending sending some string variable to my local printer. So what i wanted to do is, i want to delete a particular file from folder which is copied to the folder prior to my print command.

Its like this.. Copy the file to the //debug folder, after printing is finished delete the file. I am bit confused how to understand my printing job is done. Below are my codes.

private void print_Click(object sender, EventArgs e)
    {
        string s = image_print() + Print_image();
        PrintFactory.sendTextToLPT1(s);
        /*string Filename = img_path.Text;
        MessageBox.Show("file", Filename);
        // if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
        //   return;
        File.Delete(Path.Combine(@"E:\Debug", Filename));*/
    }

private string image_print()
    {
        OpenFileDialog ofd = new OpenFileDialog();
        string path = "";
        string full_path = "";
        string filename_noext = "";
        ofd.InitialDirectory = @"C:\ZTOOLS\FONTS";
        ofd.Filter = "GRF files (*.grf)|*.grf";
        ofd.FilterIndex = 2;
        ofd.RestoreDirectory = true;

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            filename_noext = System.IO.Path.GetFileName(ofd.FileName);
            path = Path.GetFullPath(ofd.FileName);
            img_path.Text = filename_noext;
            //MessageBox.Show(filename_noext, "Filename");
            // MessageBox.Show(full_path, "path");
            //move file from location to debug
            string replacepath = @"E:\Debug";
            string fileName = System.IO.Path.GetFileName(path);
            string newpath = System.IO.Path.Combine(replacepath, fileName);
            if (!System.IO.File.Exists(filename_noext))
                System.IO.File.Copy(path, newpath);

        }
        StreamReader test2 = new StreamReader(img_path.Text);
        string s = test2.ReadToEnd();
        return s;
    }

    private string Print_image()
    {
        //passing some commands and returns its as a sting "S"
        return s;
    }

And in my separate class function i have instructions to deal with the printer. SO below is the codes that goes for my print.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.IO;
namespace DVZebraPrint
{
public class Print
{
    public const short FILE_ATTRIBUTE_NORMAL = 0x80;
    public const short INVALID_HANDLE_VALUE = -1;
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const uint CREATE_NEW = 1;
    public const uint CREATE_ALWAYS = 2;
    public const uint OPEN_EXISTING = 3;

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
        uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
        uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    public static void sendTextToLPT1(String receiptText)
    {
        IntPtr ptr = CreateFile("LPT1", GENERIC_WRITE, 0,
                 IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

        /* Is bad handle? INVALID_HANDLE_VALUE */
        if (ptr.ToInt32() == -1)
        {
            /* ask the framework to marshall the win32 error code to an exception */
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }
        else
        {
            FileStream lpt = new FileStream(ptr, FileAccess.ReadWrite);
            Byte[] buffer = new Byte[2048];
            //Check to see if your printer support ASCII encoding or Unicode.
            //If unicode is supported, use the following:
            //buffer = System.Text.Encoding.Unicode.GetBytes(Temp);
            buffer = System.Text.Encoding.ASCII.GetBytes(receiptText);
            lpt.Write(buffer, 0, buffer.Length);
            lpt.Close();
        }
      }
    }
   }

Solution

  • you should return the file path only from image_print() function. then after printing the string delete that file.

    private string image_print()
    {
        ...Your code
        string newpath = string.Empty;
        if (!System.IO.File.Exists(filename_noext))
            System.IO.File.Copy(path, newpath);
        return newpath;
    }
    

    And read the string from that file in your print button click event

    private void print_Click(object sender, EventArgs e)
    {
        string filePath = image_print();
    
        StreamReader test2 = new StreamReader(filePath);
        string s = test2.ReadToEnd();
        test2.Close();
    
        s += Print_image();
        PrintFactory.sendTextToLPT1(s);
        System.IO.File.Delete(filePath); //Now delete the file which you have copied in image_print() method.
    }