您的位置:首页 > 其它

VC如何创建文件夹,并设置为只读共享

2013-08-20 11:18 543 查看
目前,我正在参与的项目需要在本机上创建一个文件夹,并将其设置为只读共享,其他用户可以通过局域网读取该文件夹内的文件。环境是XP+VC6.0。

创建文件夹使用的命令是CreateDirectory("F:\\TEMP", NULL);

使用WIN32 API设置文件夹为共享的命令是NetShareAdd();

具体方法见:http://www.haogongju.net/art/827019

但是这里有一个问题,SHARE_INFO_2中的shi2_permissions对于Windows XP无效,你可以设为任意值,但对文件夹的共享读写权限不起作用。

因此使用SHARE_INFO_2是无法设置文件夹为只读共享的。文章中提供了另一种设置的方法,但本人觉得太繁杂。

于是借鉴文章最后提到的方法使用SHARE_INFO_502来设置。由于作者只是给出了一个方向,并未提出具体的解决方案,所以需要自己想办法。

遇到的困难集中在PSECURITY_DESCRIPTOR shi502_security_descriptor参数的设置上,这个参数设置很繁琐。

经过搜索后,发现使用这种方法的人很少,网上的内容具有参考价值的少之又少。

最后本人难得从国外的网站上发现一个范例,能够很好的解决该问题,主要功能就是设置PSECURITY_DESCRIPTOR shi502_security_descriptor参数。

贴出来大家共享一下,同时为后来者提供一个参考,避免走弯路。

// create the SID representing everyone
SID_IDENTIFIER_AUTHORITY world_auth = SECURITY_WORLD_SID_AUTHORITY;
if (!AllocateAndInitializeSid(&world_auth,
1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &sid))
{
res = GetLastError();
goto error;
}

// create an ACL with read access for everyone,
// note GENERIC_READ|GENERIC_EXECUTE seem to correspond to
// read only access on a share but I haven't seen this documented
EXPLICIT_ACCESS access;
access.grfAccessPermissions = GENERIC_READ|GENERIC_EXECUTE;
access.grfAccessMode = SET_ACCESS;
access.grfInheritance = NO_INHERITANCE;
access.Trustee.pMultipleTrustee = 0;
access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
access.Trustee.ptstrName = (LPSTR)sid;
res = SetEntriesInAclA(1, &access, 0, &dacl);
if (res != ERROR_SUCCESS)
{
goto error;
}

// create empty security descriptor
SECURITY_DESCRIPTOR sd;
if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
{
res = GetLastError();
goto error;
}

// add the ACL to the security descriptor
if (!SetSecurityDescriptorDacl(&sd, TRUE, dacl, FALSE))
{
res = GetLastError();
goto error;
}

// create the share
SHARE_INFO_502 info;
info.shi502_netname = (LPTSTR)wshare;
info.shi502_type = STYPE_DISKTREE;
info.shi502_remark = (LPTSTR)L"";
info.shi502_permissions = ACCESS_ALL;
info.shi502_max_uses = -1;
info.shi502_current_uses = 0;
info.shi502_path = (LPTSTR)wpath;
info.shi502_passwd = (LPTSTR)L"";
info.shi502_reserved = 0;
info.shi502_security_descriptor = &sd;
res = NetShareAdd((LPTSTR)wserver, 502, (LPBYTE)&info, 0);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: