在驱动中往往需要删除某些文件 但是有些文件是只读的 就不能直接删除了,需要先修改文件属性去掉只读

具体代码如下:

NTSTATUS DeleteFile(WCHAR *szFileName)
{
	OBJECT_ATTRIBUTES objAttributes	= {0};
	IO_STATUS_BLOCK iosb = {0};
	HANDLE handle = NULL;
	FILE_DISPOSITION_INFORMATION disInfo = {0};
	UNICODE_STRING uFileName = {0};
	NTSTATUS status = 0;

	RtlInitUnicodeString(&uFileName, szFileName);

	InitializeObjectAttributes(&objAttributes, 
		&uFileName,
		OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
		NULL,
		NULL);

	status = ZwCreateFile(
		&handle, 
		SYNCHRONIZE | FILE_WRITE_DATA | DELETE,
		&objAttributes, 
		&iosb, 
		NULL, 
		FILE_ATTRIBUTE_NORMAL,
		FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
		FILE_OPEN,
		FILE_SYNCHRONOUS_IO_NONALERT | FILE_DELETE_ON_CLOSE, 
		NULL, 
		0);
	if (!NT_SUCCESS(status)) 
	{
		if (status == STATUS_ACCESS_DENIED)
		{
			KdPrint(("尝试修改文件属性"));
			status = ZwCreateFile(
				&handle, 
				SYNCHRONIZE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
				&objAttributes, 
				&iosb, 
				NULL, 
				FILE_ATTRIBUTE_NORMAL,
				FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
				FILE_OPEN,
				FILE_SYNCHRONOUS_IO_NONALERT, 
				NULL, 
				0);
			if (NT_SUCCESS(status)) 
			{
				FILE_BASIC_INFORMATION        basicInfo = {0};

				status = ZwQueryInformationFile(handle, &iosb,
					&basicInfo, sizeof(basicInfo), FileBasicInformation);
				if (!NT_SUCCESS(status)) 
				{
					KdPrint(("ZwQueryInformationFile(%wZ) failed(%x)\n", &uFileName, status));
				}

				basicInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
				status = ZwSetInformationFile(handle, &iosb,
					&basicInfo, sizeof(basicInfo), FileBasicInformation);
				if (!NT_SUCCESS(status)) 
				{
					KdPrint(("ZwSetInformationFile(%wZ) failed(%x)\n", &uFileName, status));
				}

				ZwClose(handle);
				status = ZwCreateFile(
					&handle, 
					SYNCHRONIZE | FILE_WRITE_DATA | DELETE,
					&objAttributes, 
					&iosb, 
					NULL, 
					FILE_ATTRIBUTE_NORMAL,
					FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
					FILE_OPEN,
					FILE_SYNCHRONOUS_IO_NONALERT | FILE_DELETE_ON_CLOSE, 
					NULL, 
					0);
			}
		}

		if (!NT_SUCCESS(status)) 
		{
			KdPrint(("ZwCreateFile(%wZ) failed(%x)\n", &uFileName, status));
			return status;
		}
	}

	disInfo.DeleteFile = TRUE;
	status = ZwSetInformationFile(handle, &iosb,
		&disInfo, sizeof(disInfo), FileDispositionInformation);
	if (!NT_SUCCESS(status)) 
	{
		KdPrint(("ZwSetInformationFile(%wZ) failed(%x)\n", &uFileName, status));
		return status;
	}

	ZwClose(handle);
	return status;
}

这种删文件如果是文件被占用的话还是删不掉,至于怎么删掉被占用的文件 下次有时间分享一个文件粉碎机的源码~