如何使用c#共享和取消共享Windows文件夹

时间:2015-03-16 15:25:26

标签: c# windows share

我必须与用户共享一个文件夹,并使用c#以编程方式取消共享。 我可以使用Win32_Share类的InvokeMethod共享文件夹。

            int IsShared = 0;
            ManagementClass mc = new ManagementClass("Win32_Share");

            object[] methodargs = { folderPath, shareName, "0" };

            object result = mc.InvokeMethod("Create", methodargs);


            if ((uint)result != 0)
            {
                IsShared = 1;
                return IsShared;
            }
            else
                return IsShared;

但是如何为特定用户做到这一点?

另请告诉我如何取消共享? Win32_Share类有delete()方法。但是我无法使用它取消共享。

2 个答案:

答案 0 :(得分:1)

也许不是最好的方法,但我最后默默地调用命令行,它对我有用:

分享:

        var folderName = "your_shared_folder_name";
        var targetDir = "your_folders_target_path";
        var process = new Process();

        process.StartInfo = new ProcessStartInfo()
        {
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            ErrorDialog = false,
            WindowStyle = ProcessWindowStyle.Hidden,
            FileName = "cmd.exe",
            Arguments = $"/C net share {folderName}=\"{targetDir}\" /Grant:Everyone,READ"
        };

        process.Start();
        process.WaitForExit();

注意 / Grant:Everyone,READ 。这就是我想要的,但你可能想稍微弄清楚这一部分。

要删除:

    var folderName = "your_shared_folder_name";
    var process = new Process();
    process.StartInfo = new ProcessStartInfo()
    {
        UseShellExecute = false,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        ErrorDialog = false,
        WindowStyle = ProcessWindowStyle.Hidden,
        FileName = "cmd.exe",
        Arguments = $"/C net share \"{folderName}\" /delete"
    };

    process.Start();
    process.WaitForExit();

答案 1 :(得分:0)

检查以下

 private void shareDir(string p)
    {
        string shareName = "testshare";
        string shareDesc = "This is a test share kekelar2000";
        string path = p;

        SHARE_INFO_502 info = new SHARE_INFO_502();
        info.shi502_netname = shareName;
        info.shi502_type = SHARE_TYPE.STYPE_DISKTREE;
        info.shi502_remark = shareDesc;
        info.shi502_permissions = 0;    // ignored for user-level security
        info.shi502_max_uses = 1;
        info.shi502_current_uses = 1;
        info.shi502_path = path;
        info.shi502_passwd = null;        // ignored for user-level security
        info.shi502_reserved = 0;
        info.shi502_security_descriptor = IntPtr.Zero;

        uint error = 0;
        uint result = NetShareAdd(Dns.GetHostName(), 502, ref info, out error);
    }