【发布时间】:2012-03-18 22:48:45
【问题描述】:
我试图从 WinApi 函数中编组 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# 中不起作用?
【问题讨论】:
-
什么部分不起作用。 CreateFile 还是 SetFileTime?
-
对不起。 SetFileTime 不起作用。
-
为什么不使用提供的 .NET API 而不是尝试编写 C++?
-
你得到了什么错误? (不要忘记指定 SetLastError=true:pinvoke.net/default.aspx/kernel32/SetFileTime.html)
-
“不起作用”是什么意思?