Skip to content

Commit 38c9642

Browse files
committed
fix: changed File.Open method to fix issue lukevp#234 (comment)
1 parent 8ede501 commit 38c9642

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

ESCPOS_NET.ConsoleTest/Program.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ static void Main(string[] args)
126126
if (int.TryParse(c, out int chosen) && chosen > 0)
127127
{
128128
usbPort = usboptions[chosen - 1].DevicePath;
129+
Console.WriteLine(usbPort);
129130
}
130131
}
131132
printer = new USBPrinter(usbPort);

ESCPOS_NET/Printers/USBPrinter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ public USBPrinter(string usbPath)
1212
//keeping separate file streams performs better
1313
//while using 1 file stream printers were having intermittent issues while printing
1414
//your milege may vary
15-
_rfile = File.Open(usbPath, FileMode.Open, FileAccess.Read);
16-
_wfile = File.Open(usbPath, FileMode.Open, FileAccess.Write);
15+
_rfile = DeviceFile.OpenDevice(usbPath, FileAccess.Read);
16+
_wfile = DeviceFile.OpenDevice(usbPath, FileAccess.Write);
1717
Writer = new BinaryWriter(_wfile);
1818
Reader = new BinaryReader(_rfile);
1919
}

ESCPOS_NET/Utils/DeviceFile.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System;
2+
using System.IO;
3+
using System.Runtime.InteropServices;
4+
using Microsoft.Win32.SafeHandles;
5+
6+
public static class DeviceFile
7+
{
8+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
9+
public static extern SafeFileHandle CreateFile(
10+
string lpFileName,
11+
uint dwDesiredAccess,
12+
uint dwShareMode,
13+
IntPtr lpSecurityAttributes,
14+
uint dwCreationDisposition,
15+
uint dwFlagsAndAttributes,
16+
IntPtr hTemplateFile);
17+
18+
public static FileStream OpenDevice(string devicePath, FileAccess access)
19+
{
20+
const uint OPEN_EXISTING = 3;
21+
const uint FILE_ATTRIBUTE_NORMAL = 0x80;
22+
uint desiredAccess = access == FileAccess.Read ? 0x80000000 : 0x40000000; // GENERIC_READ or GENERIC_WRITE
23+
24+
SafeFileHandle handle = CreateFile(
25+
devicePath,
26+
desiredAccess,
27+
0, // No sharing
28+
IntPtr.Zero,
29+
OPEN_EXISTING,
30+
FILE_ATTRIBUTE_NORMAL,
31+
IntPtr.Zero);
32+
33+
if (handle.IsInvalid)
34+
throw new IOException("Unable to open device", Marshal.GetLastWin32Error());
35+
36+
return new FileStream(handle, access);
37+
}
38+
}

0 commit comments

Comments
 (0)