Search code examples
c#timestamprowversion

How to read timestamp type's data from sql server using C#?


I get the result in .NET like this:

var lastRowVersion = SqlHelper.ExecuteScalar(connStr, CommandType.Text, "select
top 1 rowversion from dbo.sdb_x_orginfo order by rowversion desc");

The result is a byte array [0]= 0,[1]=0,[2]=0,[3]=0,[4]=0,[5]=0,[6]=30,[7]=138, but the result in SQL Server is 0x0000000000001E8A.

How can I get the value "0x0000000000001E8A" in .NET?


Solution

  • If you just want to convert byte[] to a System.Int64 (aka long) then use BitConverter.ToInt64:

    SqlBinary binary = /* ... */;
    long value = BitConverter.ToInt64(binary.Value, 0); // 0 is the start index in the byte array
    

    To display it as a hex string, you can use the X format specifier, e.g.:

    Console.WriteLine("Value is 0x{0:X}.", value);