我尝试在我的电脑中共享一个本地文件夹 - 代码如下所示,取自互联网并出现在很多地方,但不能正常工作。 我错过了什么吗?
private void button1_Click(object sender, EventArgs e)
{
// Create a ManagementClass object
ManagementClass managementClass = new
ManagementClass("Win32_Share");
// Create ManagementBaseObjects for in and out parameters
ManagementBaseObject inParams =
managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
// Set the input parameters
inParams["Description"] = "My Files Share";
inParams["Name"] = "My Files Share";
inParams["Path"] = @"C:\folder";
inParams["Type"] = 0x0; // Disk Drive
// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams,
null);
//Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory.");
}
}
答案 0 :(得分:0)
首先,问题是许可。我试图通过CMD进行网络共享,但只有当我运行CMD作为管理员共享操作时,它才起作用。
在C#,Visual Studio中你必须以管理员身份运行,然后才能运行。这是我的代码:
try
{
ManagementClass managementClass = new ManagementClass("Win32_Share");
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
inParams["Description"] = Description;
inParams["Name"] = ShareName;
inParams["Path"] = folderPath;
inParams["Type"] = 0; //Disk Drive
inParams["MaximumAllowed"] = null;
inParams["Password"] = null;
inParams["Access"] = null;
ManagementBaseObject outParams;
outParams = managementClass.InvokeMethod("Create", inParams, null);
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
throw new Exception();
ManagementObject share = new ManagementObject(managementClass.Path + ".Name='" + ShareName + "'");
}
catch
{
MessageBox.Show("You must run the program as administrator", "N.U.C", MessageBoxButtons.OK, MessageBoxIcon.Information);
Environment.Exit(1);
}
答案 1 :(得分:0)
代码没问题。如果您希望用IDE调试程序,那么非常简单,如果您使用Visual Studio作为IDE,只需使用Administrator运行VS并打开您的项目。