Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I delete a directory with read-only files in C#?
    text
    copied!<p>I need to delete a directory that contains read-only files. Which approach is better:</p> <ul> <li><p>Using <code>DirectoryInfo.Delete()</code>, or,</p></li> <li><p><code>ManagementObject.InvokeMethod("Delete")</code>? </p></li> </ul> <p>With <code>DirectoryInfo.Delete()</code>, I have to manually turn off the read-only attribute for each file, but <code>ManagementObject.InvokeMethod("Delete")</code> doesn't appear to need to. Is there any situation where one is more preferable to the other?</p> <p>Sample code (test.txt is read only).</p> <h3>First way:</h3> <pre><code>DirectoryInfo dir = new DirectoryInfo(@"C:\Users\David\Desktop\"); dir.CreateSubdirectory("Test"); DirectoryInfo test = new DirectoryInfo(@"C:\Users\David\Desktop\Test\"); File.Copy(@"C:\Users\David\Desktop\test.txt", @"C:\Users\David\Desktop\Test\test.txt"); File.SetAttributes(@"C:\Users\David\Desktop\Test\test.txt", FileAttributes.Archive); test.Delete(true); </code></pre> <h3>Second way:</h3> <pre><code>DirectoryInfo dir = new DirectoryInfo(@"C:\Users\David\Desktop\"); dir.CreateSubdirectory("Test"); DirectoryInfo test = new DirectoryInfo(@"C:\Users\David\Desktop\Test\"); File.Copy(@"C:\Users\David\Desktop\test.txt", @"C:\Users\David\Desktop\Test\test.txt"); string folder = @"C:\Users\David\Desktop\Test"; string dirObject = "Win32_Directory.Name='" + folder + "'"; using (ManagementObject managementObject = new ManagementObject(dirObject)) { managementObject.Get(); ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null, null); // ReturnValue should be 0, else failure if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0) { } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload