开发者

Are Windows Services Restricted from Reading from %WINDIR% (C:\Windows)?

开发者 https://www.devze.com 2023-02-16 05:24 出处:网络
I\'ve got an application running as a Windows service that wants to read a file specified by a relative path. Since the service is running under C:\\Windows\\system32 (on Server 2003 and Windows 7), I

I've got an application running as a Windows service that wants to read a file specified by a relative path. Since the service is running under C:\Windows\system32 (on Server 2003 and Windows 7), I figure it should be reading the file from there. However, the file read always fails.

I put together some simple test code to try to open a file for reading, using an absolute path. While the service succeeds for fil开发者_如何学Pythones such as C:\Temp\foo.txt, it always fails for files like C:\Windows\foo.txt and C:\Windows\system32\foo.txt . GetLastError() returns 2.

Am I running into an access issue? I couldn't find authoritative documentation on this. Is there any workaround?

Update:

The file test code is generic and straightforward:

std::ofstream out;
//...

std::string fileName("C:\\Windows\\system32\\Foo.txt");

hFile = CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile == INVALID_HANDLE_VALUE) {
  out << "Could not create file handle! (" << GetLastError() << ")" << std::endl;
}
else {
  out << "Successfully opened file!" << std::endl;
  CloseHandle(hFile);
}


Try running the windows service from Local System account. By default the service may be running from "Network Service" account. To change the settings, Open Windows Service Manager (Run-> services.msc) and double-click your service. On property window select 2nd Tab "Log On" and change it to run with Local System account.


Error code 2 is ERROR_FILE_NOT_FOUND so it's likelier that the path you give simply does not exist or the file does not exist in that path. Without the relevant flags from CreateFile it's hard to give you a better answer.

But generally - under default conditions - a service would be allowed to read in that folder.

One more thing came to mind. How do you obtain the path (C:\Windows in your case)? The proper means are to use the API (e.g. GetWindowsDirectory) for this and not hardcode it.

0

精彩评论

暂无评论...
验证码 换一张
取 消