Click here to Skip to main content
15,888,224 members
Home / Discussions / C#
   

C#

 
AnswerRe: Emailing Image To Tumblr Pin
JBHowl3-Jan-15 3:56
JBHowl3-Jan-15 3:56 
GeneralRe: Emailing Image To Tumblr Pin
Richard MacCutchan3-Jan-15 5:15
mveRichard MacCutchan3-Jan-15 5:15 
GeneralRe: Emailing Image To Tumblr Pin
Dave Kreskowiak3-Jan-15 8:24
mveDave Kreskowiak3-Jan-15 8:24 
GeneralRe: Emailing Image To Tumblr Pin
JBHowl5-Jan-15 4:19
JBHowl5-Jan-15 4:19 
GeneralRe: Emailing Image To Tumblr Pin
Dave Kreskowiak5-Jan-15 4:41
mveDave Kreskowiak5-Jan-15 4:41 
GeneralRe: Emailing Image To Tumblr Pin
JBHowl6-Jan-15 3:43
JBHowl6-Jan-15 3:43 
AnswerRe: Emailing Image To Tumblr Pin
JBHowl10-Jan-15 2:48
JBHowl10-Jan-15 2:48 
QuestionTrouble handling DeviceIoControl to retrieve USN data Pin
Mandelnuss3-Jan-15 0:46
Mandelnuss3-Jan-15 0:46 
I am having trouble with DeviceIoControl() and control code FSCTL_ENUM_USN_DATA and I am also having difficulties understanding the documentation for FSCTL_ENUM_USN_DATA.

I created the structs for MFT_ENUM_DATA and USN_RECORD_V3 and passed them as I understood the documentation, as pointers.

However, the first and only USN record I get in return (the values of the USN_RECORD_V3 buffer) is only garbage. Also, the outBufferSize should be 555 (explained at the doc for USN_RECORD_V3), but if I exceed 175 bytes, I get a System.AccessViolationError.

How to calculate outBufferSize:
C++
MaximumChangeJournalRecordSize =
    ( (MaximumComponentLength - 1) * sizeof(WCHAR)
    + sizeof(USN_RECORD_V3) );


I would appreciate if you could help me finding the mistake in my code or in my thought process. In advance, a lot of thanks to you guys!



Edit: Problematic code starts below comment:
// ENUM USN DATA




Program.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;

public class Win32
{
    /// <summary>
    /// Represents an update sequence number (USN) change journal, its records, and its capacity.
    /// This structure is the output buffer for the FSCTL_QUERY_USN_JOURNAL control code.
    /// Minimum supported client: Windows XP [desktop apps only]
    /// Minimum supported server: Windows Server 2003 [desktop apps only]
    /// </summary>
    /// <see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365721%28v=vs.85%29.aspx"/>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct USN_JOURNAL_DATA_V0
    {
        public UInt64 UsnJournalId;
        public Int64 FirstUsn;
        public Int64 NextUsn;
        public Int64 LowestValidUsn;
        public Int64 MaxUsn;
        public UInt64 MaximumSize;
        public UInt64 AllocationDelta;
    }

    /// <summary>
    /// Represents an update sequence number (USN) change journal, its records, and its capacity.
    /// This structure is the output buffer for the FSCTL_QUERY_USN_JOURNAL control code.
    /// Minimum supported client: Windows 8 [desktop apps only]
    /// Minimum supported server: Windows Server 2012 [desktop apps only]
    /// </summary>
    /// <see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/hh802707%28v=vs.85%29.aspx"/>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct USN_JOURNAL_DATA_V1
    {
        public UInt64 UsnJournalId;
        public Int64 FirstUsn;
        public Int64 NextUsn;
        public Int64 LowestValidUsn;
        public Int64 MaxUsn;
        public UInt64 MaximumSize;
        public UInt64 AllocationDelta;
        public UInt16 MinSupportedMajorVersion;
        public UInt16 MaxSupportedMajorVersion;
    }

    /// <summary>
    /// Contains the information for an update sequence number (USN) change journal version 3.0 record. The version 2.0 record is defined by the USN_RECORD_V2 structure (also called USN_RECORD structure).
    /// </summary>
    /// <see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/hh802708%28v=vs.85%29.aspx"/>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct USN_RECORD_V3
    {
        public UInt32 RecordLength;
        public UInt16 MajorVersion;
        public UInt16 MinorVersion;
        public Byte FileReferenceNumber;
        public Byte ParentFileReferenceNumber;
        public Int64 Usn;
        public FILETIME TimeStamp;
        public UInt32 Reason;
        public UInt32 SourceInfo;
        public UInt32 SecurityId;
        public UInt32 FileAttributes;
        public UInt16 FileNameLength;
        public UInt16 FileNameOffset;
        public Char FileName;
    }

    /// <summary>
    /// Contains information defining the boundaries for and starting place of an enumeration of update sequence number (USN) change journal records for ReFS volumes. It is used as the input buffer for the FSCTL_ENUM_USN_DATA control code.
    /// </summary>
    /// <see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/hh802704%28v=vs.85%29.aspx"/>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct MFT_ENUM_DATA_V1
    {
        public UInt64 StartFileReferenceNumber;
        public Int64 LowUsn;
        public Int64 HighUsn;
        public UInt16 MinMajorVersion;
        public UInt16 MaxMajorVersion;
    }

    /// <summary>
    /// Sends the 'dwIoControlCode' to the device specified by 'hDevice'.
    /// </summary>
    /// <param name="hDevice">IntPtr handle to handle to a file, directory, or device to receive 'dwIoControlCode'. Obtained by calling CreateFile.</param>
    /// <param name="dwIoControlCode">Device IO Control Code to send</param>
    /// <param name="lpInBuffer">Input buffer if required</param>
    /// <param name="nInBufferSize">Size of input buffer</param>
    /// <param name="lpOutBuffer">Output buffer if required</param>
    /// <param name="nOutBufferSize">Size of output buffer</param>
    /// <param name="lpBytesReturned">Number of bytes returned in output buffer</param>
    /// <param name="lpOverlapped">IntPtr to an 'OVERLAPPED' structure</param>
    /// <returns>'true' if successful, otherwise 'false'</returns>
    /// <see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx"/>
    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeviceIoControl(
        SafeHandle hDevice,
        UInt32 dwIoControlCode,
        IntPtr lpInBuffer,
        UInt32 nInBufferSize,
        out IntPtr lpOutBuffer,
        UInt32 nOutBufferSize,
        out UInt32 lpBytesReturned,
        IntPtr lpOverlapped
    );

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeviceIoControl(
        SafeHandle hDevice,
        UInt32 dwIoControlCode,
        IntPtr lpInBuffer,
        UInt32 nInBufferSize,
        out USN_JOURNAL_DATA_V1 lpOutBuffer,
        UInt32 nOutBufferSize,
        out UInt32 lpBytesReturned,
        IntPtr lpOverlapped
    );

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeviceIoControl(
        SafeHandle hDevice,
        UInt32 dwIoControlCode,
        ref MFT_ENUM_DATA_V1 lpInBuffer,
        UInt32 nInBufferSize,
        out USN_RECORD_V3 lpOutBuffer,
        UInt32 nOutBufferSize,
        out UInt32 lpBytesReturned,
        IntPtr lpOverlapped
    );

    // Use interop to call the CreateFile function. 
    // For more information about CreateFile, 
    // see the unmanaged MSDN reference library.
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern SafeFileHandle CreateFile(
        string lpFileName,
        uint dwDesiredAccess,
        uint dwShareMode,
        IntPtr lpSecurityAttributes,
        uint dwCreationDisposition,
        uint dwFlagsAndAttributes,
        IntPtr hTemplateFile
    );

    /// <summary>
    /// Sets the number of bytes specified by 'size' of the memory associated with the argument 'ptr' 
    /// to zero.
    /// </summary>
    /// <param name="ptr"></param>
    /// <param name="size"></param>
    [DllImport("kernel32.dll")]
    public static extern void ZeroMemory(IntPtr ptr, int size);
}

namespace UsnTest01
{

    class Program
    {
        #region constants
        public const short FILE_ATTRIBUTE_NORMAL = 0x80;
        public const short INVALID_HANDLE_VALUE = -1;
        public const UInt32 GENERIC_READ = 0x80000000;
        public const UInt32 GENERIC_WRITE = 0x40000000;
        public const UInt32 FILE_SHARE_READ = 0x00000001;
        public const UInt32 FILE_SHARE_WRITE = 0x00000002;
        public const UInt32 CREATE_NEW = 1;
        public const UInt32 CREATE_ALWAYS = 2;
        public const UInt32 OPEN_EXISTING = 3;

        private const UInt32 FILE_DEVICE_FILE_SYSTEM = 0x00000009;
        private const UInt32 METHOD_NEITHER = 3;
        private const UInt32 METHOD_BUFFERED = 0;
        private const UInt32 FILE_ANY_ACCESS = 0;
        private const UInt32 FILE_SPECIAL_ACCESS = 0;
        private const UInt32 FILE_READ_ACCESS = 1;
        private const UInt32 FILE_WRITE_ACCESS = 2;
        public const UInt32 FSCTL_QUERY_USN_JOURNAL = (FILE_DEVICE_FILE_SYSTEM << 16) | (FILE_ANY_ACCESS << 14) | (61 << 2) | METHOD_BUFFERED;
        public const UInt32 FSCTL_ENUM_USN_DATA = (FILE_DEVICE_FILE_SYSTEM << 16) | (FILE_ANY_ACCESS << 14) | (44 << 2) | METHOD_NEITHER;
        public const UInt32 FSCTL_READ_USN_JOURNAL = (FILE_DEVICE_FILE_SYSTEM << 16) | (FILE_ANY_ACCESS << 14) | (46 << 2) | METHOD_NEITHER;
        #endregion constants

        static void Main(string[] args)
        {

            // GET VOLUME HANDLE

            SafeFileHandle handleValue = null;
            handleValue = Win32.CreateFile(
                @"\\.\C:",
                GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
                IntPtr.Zero,
                OPEN_EXISTING,
                0,
                IntPtr.Zero);

            if (handleValue.IsInvalid)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            // GET USN JOURNAL ID

            Win32.USN_JOURNAL_DATA_V1 ujd = new Win32.USN_JOURNAL_DATA_V1();
            uint lpBytesReturned;

            bool retJournalId = Win32.DeviceIoControl(
                handleValue,
                FSCTL_QUERY_USN_JOURNAL,
                IntPtr.Zero,
                0,
                out ujd,
                (uint)Marshal.SizeOf(ujd),
                out lpBytesReturned,
                IntPtr.Zero);

            Console.WriteLine("Wert ist " + ujd.UsnJournalId.ToString("X4"));



            // ENUM USN DATA

            Win32.USN_RECORD_V3 usnRecordV3;
            Win32.MFT_ENUM_DATA_V1 mftEnumDataV1 = new Win32.MFT_ENUM_DATA_V1 { StartFileReferenceNumber = 0 };

            //int mftEnumDataV1BufferSize = Marshal.SizeOf(mftEnumDataV1);
            //IntPtr mftEnumDataV1BufferPointer = Marshal.AllocHGlobal(mftEnumDataV1BufferSize);
            //Marshal.StructureToPtr(mftEnumDataV1, mftEnumDataV1BufferPointer, true);
            //Win32.ZeroMemory(mftEnumDataV1BufferPointer, mftEnumDataV1BufferSize);

            // TODO "255-1" durch "MaximumComponentLength-1" ersetzen
            uint outBufferSize = (uint)((255 - 1) * sizeof(Char) + Marshal.SizeOf(typeof(Win32.USN_RECORD_V3)));
            lpBytesReturned = 0;

            bool retUsnData = false;
            while (retUsnData != true) // while non-zero value
            {
                retUsnData = Win32.DeviceIoControl(
                    handleValue,
                    FSCTL_ENUM_USN_DATA,
                    ref mftEnumDataV1,
                    (uint)Marshal.SizeOf(mftEnumDataV1),
                    out usnRecordV3,
                    175, //max without exception is 175. Should be var `outBufferSize`.
                    out lpBytesReturned,
                    IntPtr.Zero);

                //mftEnumDataV1.StartFileReferenceNumber = usnRecordV3.RecordLength;
                //object test = Marshal.PtrToStructure(mftEnumDataV1BufferPointer, typeof(Win32.MFT_ENUM_DATA_V1));
                //Marshal.WriteInt64(mftEnumDataV1BufferPointer, usnRecordV3.RecordLength);
                //Marshal.StructureToPtr(mftEnumDataV1, mftEnumDataV1BufferPointer, true);

            }

            int r1 = Marshal.GetLastWin32Error();
            int r2 = Marshal.GetHRForLastWin32Error();

            if (retUsnData == false)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

        }
    }
}

AnswerRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Richard MacCutchan3-Jan-15 0:57
mveRichard MacCutchan3-Jan-15 0:57 
GeneralRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Mandelnuss3-Jan-15 1:18
Mandelnuss3-Jan-15 1:18 
GeneralRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Richard MacCutchan3-Jan-15 1:50
mveRichard MacCutchan3-Jan-15 1:50 
GeneralRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Mandelnuss3-Jan-15 3:53
Mandelnuss3-Jan-15 3:53 
GeneralRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Richard MacCutchan3-Jan-15 4:46
mveRichard MacCutchan3-Jan-15 4:46 
GeneralRe: Trouble handling DeviceIoControl to retrieve USN data Pin
Mandelnuss3-Jan-15 5:20
Mandelnuss3-Jan-15 5:20 
QuestionLogic of prime numbers Pin
Member 113371082-Jan-15 12:44
Member 113371082-Jan-15 12:44 
AnswerRe: Logic of prime numbers Pin
BillWoodruff2-Jan-15 13:14
professionalBillWoodruff2-Jan-15 13:14 
GeneralRe: Logic of prime numbers Pin
Richard MacCutchan2-Jan-15 22:03
mveRichard MacCutchan2-Jan-15 22:03 
GeneralRe: Logic of prime numbers Pin
Pete O'Hanlon2-Jan-15 23:23
mvePete O'Hanlon2-Jan-15 23:23 
GeneralRe: Logic of prime numbers Pin
BillWoodruff3-Jan-15 0:42
professionalBillWoodruff3-Jan-15 0:42 
GeneralRe: Logic of prime numbers Pin
Richard MacCutchan3-Jan-15 0:47
mveRichard MacCutchan3-Jan-15 0:47 
GeneralRe: Logic of prime numbers Pin
BillWoodruff3-Jan-15 11:57
professionalBillWoodruff3-Jan-15 11:57 
GeneralRe: Logic of prime numbers Pin
Richard MacCutchan3-Jan-15 21:05
mveRichard MacCutchan3-Jan-15 21:05 
GeneralRe: Logic of prime numbers Pin
BillWoodruff3-Jan-15 21:21
professionalBillWoodruff3-Jan-15 21:21 
GeneralRe: Logic of prime numbers Pin
Richard MacCutchan3-Jan-15 22:02
mveRichard MacCutchan3-Jan-15 22:02 
AnswerRe: Logic of prime numbers Pin
SledgeHammer012-Jan-15 14:16
SledgeHammer012-Jan-15 14:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.