c# - 为什么这个 P/Invoke 签名不起作用?

标签 c# c++ winapi pinvoke

我试图从 WinApi 函数编码(marshal) C# 代码.. 但我明白.. 为什么她不工作!文件路径 - 正确,句柄已被使用。 谁能帮帮我?

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;
        }
    }
}

我想我弄错了..我尝试编写 C++ 代码,她工作得很好..但为什么在 C# 中不起作用?

最佳答案

来自 MSDN :

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

这应该有效:

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

关于c# - 为什么这个 P/Invoke 签名不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763012/

相关文章:

c++ - WM_QUIT 只发布线程而不是窗口?

c - SEH、访问冲突和堆栈保护页面

c# - 存储库模式 - 方法太多

java - 在关闭远程桌面连接时运行 s/w

c# - 检测 Windows 重新启动是否是由于 Windows 更新

c++ - gdb条件中断中使用的STL类型/函数,会导致程序崩溃吗?

c++ - 如何在 gdb 中配置 STL View ?

c# - Azure 函数代理响应正文不能包含大括号内的值

c# - SQL 用户类型问题

c# - C# 中任意代码块(通过大括号)的实际用途是什么