在远程计算机上创建和删除文件

时间:2014-01-02 09:43:53

标签: c# .net

我想在远程计算机上创建和删除我有管理员用户名和密码的文件。

我正在使用此代码

ConnectionOptions options = new ConnectionOptions();
    options.Username = "admin";
    options.Password = "12345";
    ManagementScope scope =  null;
    ObjectQuery query = null;
    ManagementObjectSearcher searcher = null;

    try
    {
       scope = new ManagementScope(@"\\192.168.3.125\root\CIMV2", options);
       scope.Connect();
       query = new ObjectQuery(@"SELECT * FROM CIM_Datafile WHERE name = 'c:\\c$\\Testing\\Test.txt'");
       searcher = new ManagementObjectSearcher(scope, query); // EDIT forgot to include 'scope' previously
    }
    catch(Exception ex)
    {
       Console.WriteLine(ex.Message);
       return;
    }

    foreach(ManagementObject mo in searcher.Get())
    {
       uint returnCode = (uint)mo.InvokeMethod("Delete", null);
       if (returnCode == 0)
         Console.WriteLine("File was successfully deleted");
       else
         Console.WriteLine("Deletion failed due to return code " + returnCode);
    }

但它给我无效的查询错误,我也想知道如何在远程机器上创建文件。

我甚至无法访问路径\\ 192.168.3.125 \ C $ \ Testing \ Test.txt

我的文件位置是c:\ Testing \ Test.txt

2 个答案:

答案 0 :(得分:2)

首先,你可以从机器上通过Windows资源管理器访问该文件(开始 - >运行 - > \ 192.168.3.125 \ C $ \ Testing \ Test.txt)

如果是这样的话

有什么问题
File.Delete(@"\\192.168.3.125\C$\Testing\Test.txt");

答案 1 :(得分:0)

就我而言,当我连接两台基于Windows的计算机时,您可以放置​​:

@"\\PC-NAME\NEXT-FOLDER\NEXT-FOLDER\test.txt"