iKeler
iKeler

Reputation: 73

Why doesn't this P/Invoke signature work?

I trying to marshaling C# code from WinApi functions.. But i understand.. WHYYY WHYY she dont work! Filepath - is correct, handle is taken. Can anyone help me?

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;

namespace ChangeFileTime
{

    class Program
    {

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetFileTime(IntPtr hFile, ref long lpCreationTime,
                                                            ref long lpLastAccessTime, 
                                                            ref long lpLastWriteTime);

        [DllImport("kernel32.dll")]
        public static extern IntPtr CreateFile(string lpFilename,
                                              uint dwDesiredAccess,
                                              uint dwShareMode,
                                              IntPtr SecurityAttributes,
                                              uint dwCreationDisposition,
                                              uint dwFlagsAndAttributes,
                                              IntPtr hTemplateFile);


        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        static void Main(string[] args)
        {
            const uint GENERIC_READ = 0x80000000;
            const uint OPEN_EXISTING = 3;
            const uint FILE_SHARE_WRITE = 0x00000002;
            const uint FILE_ATTRIBUTE_NORMAL = 128;

            IntPtr ptr = CreateFile("C:\\file.txt", GENERIC_READ,
                                                    FILE_SHARE_WRITE,
                                                    IntPtr.Zero,
                                                    OPEN_EXISTING,
                                                    FILE_ATTRIBUTE_NORMAL,
                                                    IntPtr.Zero);

            DateTime creation_time = new DateTime(1990, 12, 14);

            long file_time = creation_time.ToFileTime();
            DateTime time = DateTime.FromFileTime(file_time);

            SetFileTime(ptr, ref file_time, ref file_time, ref file_time);
            int a = 20;
        }
    }
}

I think i got mistake.. i try to write C++ code, and she work fine.. but why in C# dont work?

Upvotes: 0

Views: 496

Answers (1)

max
max

Reputation: 34447

From MSDN:

The handle must have been created using the CreateFile function with the FILE_WRITE_ATTRIBUTES

This should work:

const uint FILE_WRITE_ATTRIBUTES = 0x0100;
IntPtr ptr = CreateFile("C:\\file.txt", FILE_WRITE_ATTRIBUTES, //...

Upvotes: 3

Related Questions