tags:

views:

43

answers:

2

I have an application that opens a port to a printer(it's a bar code printer) which works on win XP but when i switch to win7 (64bit) i have a problem. Here is the code:

I am using this method to open the port:

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern SafeFileHandle CreateFile(
           String pipeName,
           uint dwDesiredAccess,
           uint dwShareMode,
           IntPtr lpSecurityAttributes,
           uint dwCreationDisposition,
           uint dwFlagsAndAttributes,
           IntPtr hTemplate);

and i call it like this:

public void OpenPort(String portName)
{
    if (String.IsNullOrEmpty(m_portName)) throw new Exception(SET_PORTNAME);
    this.m_portName = portName;
    pipeHandle = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero,
        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
}

What happens is that pipeHandle.Close=false and pipeHandle.IsInvalid=true

This is the method that sends data to the port

        private void WriteBytesToPrinter(byte[] dataBytes)
        {
            if (!IsPortOpen) throw new Exception(OPEN_PORT_ERROR);
            using (FileStream fStream = new FileStream(pipeHandle, FileAccess.Write,  
                 dataBytes.Length, true))
            {
                fStream.Write(dataBytes, 0, dataBytes.Length);
                fStream.Flush();
                fStream.Close();
            }
        }

and i get the exception:

ArgumentException
Invalid handle.
Parameter name: handle

I would really appreciate some help. Thanks.

A: 

Have you tried running the executable in WinXP compatability-mode? It could have some trouble with the new Windows driver model in Windows 7.

wwwhizz
A: 

What portName you've specified ? Have you tried:

pipeHandle = CreateFile("NONSPOOLED_LPT1", GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);

?

Dimus