Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete file on Remote Server Using WMI

Tags:

c#

wmi

wmi-query

I'm trying to delete an existing file on the remote server using WMI.

Here's my code:

string name = @"\\servername\\OCROut\\basketball.txt";

ConnectionOptions options = new ConnectionOptions(remoteServer, "username", "password", "ntlmdomain:domainName", ImpersonationLevel.Impersonate, AuthenticationLevel.Default, true, null, System.TimeSpan.MaxValue);

                            ManagementScope scope = new ManagementScope("\\\\server\\root\\cimv2", options);
                            scope.Connect();
                            var query = new ObjectQuery(string.Format("SELECT * FROM CIM_Datafile WHERE Drive = 'D' AND Name = '{0}' AND Filename = 'basketball' and Extension = 'txt'", name));
                            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                            var tobeDeleted = searcher.Get();

                            foreach (ManagementObject item in searcher.Get())
                            {
                                item.InvokeMethod("Delete", null);
                            }

The Query is working file but but my Count = 0 when i'm executing the searcher.Get() method. I tried everything, different slashes, without the drive, Filename and extension but nothing seem to be working and i know that the file exists.

Any help would be highly appreciated.

like image 903
Arka Avatar asked Sep 14 '25 03:09

Arka


1 Answers

It seems which you are passing wrong values in the params. the Name property must contain the full local path of the file, so try this :

string name = @"D:\\OCROut\\basketball.txt";
var query = new ObjectQuery(string.Format("SELECT * FROM CIM_Datafile WHERE Name = '{0}'", name));
like image 65
RRUZ Avatar answered Sep 16 '25 16:09

RRUZ