如何设置目录属性?使用WinApi CreateDirectory创建目录后,怎么设时间属性?
Hey there, let's tackle your two questions about Windows directory operations—these are pretty common tasks when working with WinAPI, so I’ll walk you through each step with code examples and key notes.
1. How to Set Directory Attributes
To modify a directory's attributes using WinAPI, you’ll use the SetFileAttributesW (wide string version, recommended for Unicode support) or SetFileAttributesA function. This works for both files and directories seamlessly.
Key Attributes You Might Set
Here are some common directory attributes you can use (combine multiple with the bitwise OR operator |):
FILE_ATTRIBUTE_READONLY: Marks the directory as read-only (note: this doesn’t prevent deleting the directory on Windows)FILE_ATTRIBUTE_HIDDEN: Hides the directory from standard file explorersFILE_ATTRIBUTE_SYSTEM: Flags the directory as a system directoryFILE_ATTRIBUTE_DIRECTORY: (Automatically set when creating the directory—you rarely need to set this manually)
Code Example (C++)
#include <windows.h> #include <iostream> int main() { LPCWSTR dirPath = L"C:\\Your\\Target\\Directory"; // Set directory to hidden + read-only BOOL result = SetFileAttributesW(dirPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY); if (result) { std::wcout << L"Directory attributes updated successfully!\n"; } else { std::wcout << L"Failed to set attributes. Error code: " << GetLastError() << std::endl; } return 0; }
Quick Notes
- Always check the return value of
SetFileAttributes—it returnsTRUEon success,FALSEon failure. UseGetLastError()to pull the specific error code if things go wrong. - If you need to clear an attribute, first fetch the current attributes with
GetFileAttributes, remove the unwanted flag, then callSetFileAttributesagain with the modified value.
2. How to Set Creation, Last Access, and Last Write Time for a Directory Created via CreateDirectory
To tweak a directory's timestamps, you’ll use the SetFileTime function. But first, you need a valid handle to the directory—since directories aren’t "regular files," you have to pass the FILE_FLAG_BACKUP_SEMANTICS flag when opening it with CreateFile.
Step-by-Step Breakdown
- Open the directory with
CreateFileusing the correct flags to get a handle. - Prepare
FILETIMEstructures for your target timestamps (convert human-readable time toFILETIMEusingSystemTimeToFileTime). - Call
SetFileTimeto apply the new timestamps. - Close the directory handle with
CloseHandle—don’t skip this!
Code Example (C++)
#include <windows.h> #include <iostream> int main() { LPCWSTR dirPath = L"C:\\Your\\Existing\\Directory"; // Open the directory to get a valid handle HANDLE hDir = CreateFileW( dirPath, FILE_WRITE_ATTRIBUTES, // Need write access to modify attributes FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, // Critical flag to open directories NULL ); if (hDir == INVALID_HANDLE_VALUE) { std::wcout << L"Failed to open directory. Error code: " << GetLastError() << std::endl; return 1; } // Let's set a specific date: 2024-01-01 12:00:00 SYSTEMTIME st = {0}; st.wYear = 2024; st.wMonth = 1; st.wDay = 1; st.wHour = 12; st.wMinute = 0; st.wSecond = 0; FILETIME ft; SystemTimeToFileTime(&st, &ft); // Set all three timestamps to the same value (pass NULL for any you want to leave unchanged) BOOL result = SetFileTime( hDir, &ft, // Creation time &ft, // Last access time &ft // Last write time ); if (result) { std::wcout << L"Directory timestamps updated successfully!\n"; } else { std::wcout << L"Failed to set timestamps. Error code: " << GetLastError() << std::endl; } // Clean up the handle CloseHandle(hDir); return 0; }
Important Reminders
- The
FILE_WRITE_ATTRIBUTESaccess right is the minimum you need to modify timestamps—don’t request more access than necessary. - If you only want to update one or two timestamps, pass
NULLfor the parameters corresponding to the ones you want to keep as-is. FILE_FLAG_BACKUP_SEMANTICSis non-negotiable here—without it,CreateFilewill fail to open the directory.
内容的提问来源于stack exchange,提问作者zet

