指定文件的创建时间 访问时间 和修改时间
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace SetFileSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetFileTime(SafeHandle hFile, ref long lpCreationTime, ref long lpLastAccessTime, ref long lpLastWriteTime);
public static void SetFileTimes(SafeHandle hFile, DateTime creationTime, DateTime accessTime, DateTime writeTime)
{
long lCreationTime = creationTime.ToFileTime();
long lAccessTime = accessTime.ToFileTime();
long lWriteTime = writeTime.ToFileTime();
if (!SetFileTime(hFile, ref lCreationTime, ref lAccessTime, ref lWriteTime))
{
throw new Win32Exception();
}
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Win32.SafeHandles.SafeFileHandle handle;
string path = "c:\\a.txt";
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 1);
handle = stream.SafeFileHandle;
if (!handle.IsInvalid)
{
DateTime dn = DateTime.Now;
long dt = dn.ToFileTime();
if (SetFileTime(handle, ref dt, ref dt, ref dt))
{
MessageBox.Show("成功!");
}
else
{
MessageBox.Show("失败!");
}
}
stream.Close();
}
}
}