All products / Saraff.TwainX.Extensions
Getting Started
This page takes you from an empty project to a scanned image using XDsm, XDs and
XCapability<T>.
1. Install
dotnet add package Saraff.TwainX.Extensions --version 1.0.3.616
Or add the package reference manually:
<ItemGroup>
<PackageReference Include="Saraff.TwainX.Extensions" Version="1.0.3.616" />
</ItemGroup>
Saraff.TwainX.Extensions depends on Saraff.TwainX 1.0.35; NuGet restores it automatically.
| Target framework | TWAIN 2.x | Stream images | Async acquisition |
|---|---|---|---|
netstandard2.0 |
Yes, with a DS2 source | Yes | Yes |
The host must still provide a TWAIN 2.x DSM and a DS2 data source. See Saraff.TwainX for platform and bitness requirements.
2. Create the Data Source Manager
XDsm is the entry point. It wraps Saraff.TwainX.TwainX and owns the session when it is created
with the convenience factory:
using Saraff.TwainX;
using Saraff.TwainX.Extensions;
var dsm = XDsm.Create(
isShowUI: true,
language: TwLanguage.ENGLISH_USA,
country: TwCountry.USA);
The factory creates a TwainX instance and disposes it together with XDsm. The default locale in
this package is RUSSIAN / BELARUS; pass explicit values for a different locale.
If the application already owns a TwainX component, share it instead:
var sharedDsm = XDsm.Create(existingTwain, isOwns: false);
existingTwain is disposed by the application, not by XDsm. XDsm still subscribes to its events
and unsubscribes in Dispose().
Keep dsm alive for the whole TWAIN session. In a WinForms or WPF application make it a field and
dispose it with the form; a short using block is only safe when no asynchronous callbacks remain.
3. Enumerate data sources
XDsm.DataSources yields one lightweight XDs wrapper per installed source. The enumeration opens
the DSM, but it does not open a source.
using System.Linq;
var sources = dsm.DataSources.ToList();
foreach (var source in sources)
{
Console.WriteLine(
$"{source.Identity.Manufacturer} {source.Identity.Name} " +
$"(TWAIN {source.Identity.ProtocolVersion}, default: {source.IsDefault}, " +
$"2.x compatible: {source.IsTwain2Compatible})");
}
XDs.Identity exposes Manufacturer, Family, Name, Version and ProtocolVersion.
IsDefault and IsTwain2Compatible are manager-level queries and do not open the source.
If the list is empty, install a TWAIN 2.x DSM and a DS2 source, and check that the process bitness matches the driver.
4. Select and open a source
The extensions have no separate Open() method. The first operation that needs the data source
uses XDs.TwainX, which selects this source, closes the previously selected source if necessary and
calls TwainX.OpenDataSource():
var source = dsm.DataSources.ElementAtOrDefault(0);
if (source == null)
{
Console.WriteLine("No TWAIN data sources found.");
return;
}
var twain = source.TwainX; // DSM and DS are now open
Console.WriteLine(twain.SourcesCount);
Source switching is lazy and cached. XDs.TwainX does not reopen an already open source. It throws
InvalidOperationException from the underlying TwainX if the previous source is still enabled;
close the active acquisition before switching.
All synchronous TWAIN calls must run on the same thread that opened the DSM. Saraff.TwainX checks
thread affinity. In a WinForms or WPF application use the UI/STA thread; the asynchronous API avoids
this restriction by creating its own session thread.
5. Configure capabilities
Capabilities are typed by the value they contain:
var resolution = source.GetCapability<float>(TwCap.XResolution);
resolution.Set(300f);
var pixelType = source.GetCapability<TwPixelType>(TwCap.IPixelType);
pixelType.Set(TwPixelType.RGB);
Console.WriteLine($"Supported operations: {resolution.IsSupported}");
XCapability<T>.Values exposes the allowed values and their current/default flags:
foreach (var value in resolution.Values)
{
Console.WriteLine($"{value.Value} current={value.IsCurrent} default={value.IsDefault}");
}
resolution.Values.First(v => v.IsDefault).Set();
The fluent Set(...) helpers return the capability so chains can continue. They accept a callback,
not a raw value:
source
.GetCapability<float>(TwCap.XResolution).Set(_ => 300f).DataSource
.GetCapability<float>(TwCap.YResolution).Set(_ => 300f).DataSource
.GetCapability<TwPixelType>(TwCap.IPixelType).Set(_ => TwPixelType.RGB).DataSource
.GetCapability<TwFF>(TwCap.ImageFileFormat).Set(_ => TwFF.Png).DataSource;
See Capabilities for conversion rules and session-bound capabilities.
6. Acquire synchronously
using System.IO;
source.NativeTransfer(
e =>
{
using (var stream = e.Stream)
using (var file = File.Create("scan.png"))
{
stream.CopyTo(file);
}
},
imageInfoCallback: e => Console.WriteLine(e.GetImageInfo().ImageWidth),
completeCallback: () => Console.WriteLine("Acquisition completed."),
errorCallback: e => Console.Error.WriteLine(e.Exception));
NativeTransfer selects and opens the source, sets ICAP_XFERMECH to SX_NATIVE, starts
acquisition and stores the callbacks for the duration of the transfer. Only one synchronous
transfer may run at a time per XDsm.
Transfer callbacks run on the TWAIN session thread. In a UI application marshal UI updates to the dispatcher if the callback is raised on a different thread.
See Image transfers for memory, memory-file and disk-file modes.
7. Acquire asynchronously
XDs.AcquireAsync uses the asynchronous API of Saraff.TwainX and does not block the caller:
using System.IO;
using Saraff.TwainX;
var options = new TwainXAcquireOptions
{
ShowUI = false,
MaxImages = 1,
Progress = new Progress<TwainXAcquisitionProgress>(p =>
Console.WriteLine($"Page {p.PageNumber}"))
};
using (var result = await source.AcquireAsync(
options,
session => session.GetCapability<TwPixelType>(TwCap.IPixelType).Set(TwPixelType.RGB)))
{
for (var i = 0; i < result.Streams.Count; i++)
{
using (var file = File.Create($"scan-{i}.png"))
{
result.Streams[i].CopyTo(file);
}
}
}
The configure callback runs on the acquisition session thread after the source is opened. Use
XCapabilitySession.GetCapability<T> inside it; do not touch XDs.TwainX from that callback.
See Asynchronous acquisition for source selection, cancellation, progress, result ownership and limitations.
8. Dispose
dsm.Dispose();
XDsm.Dispose():
- unsubscribes from all
TwainXevents; - clears the active transfer context;
- cancels the asynchronous acquisition session;
- closes the DSM and disposes the owned
TwainX(whenisOwnsistrue).
After disposal, XDsm.TwainX and XDs.AcquireAsync throw ObjectDisposedException.