How do I delete a directory with read-only files in C#?
Here is an extension method which sets Attributes
to Normal
recursively, then deletes the items:
public static void DeleteReadOnly(this FileSystemInfo fileSystemInfo)
{
var directoryInfo = fileSystemInfo as DirectoryInfo;
if (directoryInfo != null)
{
foreach (FileSystemInfo childInfo in directoryInfo.GetFileSystemInfos())
{
childInfo.DeleteReadOnly();
}
}
fileSystemInfo.Attributes = FileAttributes.Normal;
fileSystemInfo.Delete();
}
How do I delete a read-only file?
According to File.Delete's documentation,, you'll have to strip the read-only attribute. You can set the file's attributes using File.SetAttributes().
using System.IO;
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
C# Delete a Directory/File and set ReadOnly Attribute
What you are doing is you have an expressiondi.Attributes &= ~FileAttributes.ReadOnly;
that is not assigned, used etc. nowhere in the code.
Also you are mixing DirectoryInfo and FileAttributes. This is just wrong. What you really want (from the description) is to set file not to be read only and then delete it.
So, you have to it like this
File.SetAttributes("FileToDelete", File.GetAttributes("FileToDelete") & ~FileAttributes.ReadOnly);
File.Delete("FileToDelete");
also please note that the exception you're getting can still occur if you will not have sufficient permissions https://msdn.microsoft.com/en-us/library/system.io.file.setattributes%28v=vs.110%29.aspx
as for the directories
new DirectoryInfo("DirectoryToDelete").Attributes &= ~FileAttributes.ReadOnly;
Removing read only attribute on a directory using C#
You could also do something like the following to recursively clear readonly (and archive, etc.) for all directories and files within a specified parent directory:
private void ClearReadOnly(DirectoryInfo parentDirectory)
{
if(parentDirectory != null)
{
parentDirectory.Attributes = FileAttributes.Normal;
foreach (FileInfo fi in parentDirectory.GetFiles())
{
fi.Attributes = FileAttributes.Normal;
}
foreach (DirectoryInfo di in parentDirectory.GetDirectories())
{
ClearReadOnly(di);
}
}
}
You can therefore call this like so:
public void Main()
{
DirectoryInfo parentDirectoryInfo = new DirectoryInfo(@"c:\test");
ClearReadOnly(parentDirectoryInfo);
}
Remove readonly attribute from directory
var di = new DirectoryInfo("SomeFolder");
di.Attributes &= ~FileAttributes.ReadOnly;
How to delete Read only folder in asp.net ,c#
As I commented earlier the problem is that you are trying to delete a folder as you were deleting a file.
You should use Directory.Delete method to delete a folder.
In the following link there is a good example on how to use it
http://msdn.microsoft.com/en-au/library/fxeahc5f(v=vs.100).aspx
public static void Main()
{
// Specify the directories you want to manipulate.
string path = @"c:\MyDir";
string subPath = @"c:\MyDir\temp";
try
{
// Determine whether the directory exists.
if (!Directory.Exists(path))
{
// Create the directory.
Directory.CreateDirectory(path);
}
if (!Directory.Exists(subPath))
{
// Create the directory.
Directory.CreateDirectory(subPath);
}
// This will succeed because subdirectories are being deleted.
Console.WriteLine("I am about to attempt to delete {0}", path);
Directory.Delete(path, true);
Console.WriteLine("The Delete operation was successful.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
How does Read-Only affect a Directory when using C#/.Net?
As Damien_The_Unbeliever mentions, if we look at the Win32 API for FILE_ATTRIBUTE_READONLY it mentions:
This attribute is not honored on directories.
See also: http://go.microsoft.com/fwlink/p/?linkid=125896
So it seems indeed that you can simply delete such directories using win32 or Explorer. .NET, however, seems to check flags on directories before deleting them. You can see this by using DotPeek or Reflector, on Directory.Delete for example. This is what's causing your "access denied" error.
EDIT:
I looked into this in a bit more detail, and it seems like it is not .NET which is throwing the access denied error. Consider the following test code:
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ReadOnlyDirTest
{
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
extern static bool RemoveDirectory(string path);
static String CreateTempDir()
{
String tempDir;
do
{
tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (Directory.Exists(tempDir));
Directory.CreateDirectory(tempDir);
return tempDir;
}
static void Main(string[] args)
{
var tempDir = CreateTempDir();
// Set readonly.
new DirectoryInfo(tempDir).Attributes |= FileAttributes.ReadOnly;
try
{
Directory.Delete(tempDir);
}
catch (Exception e)
{
Console.WriteLine("Directory.Delete: " + e.Message);
}
if (!Directory.Exists(tempDir))
Console.WriteLine("Directory.Delete deleted directory");
try
{
if (!RemoveDirectory(tempDir))
Console.WriteLine("RemoveDirectory Win32 error: " + Marshal.GetLastWin32Error().ToString());
}
catch (Exception e)
{
Console.WriteLine("RemoveDirectory: " + e.Message);
}
if (!Directory.Exists(tempDir))
Console.WriteLine("RemoveDirectory deleted directory");
// Try again without readonly, for both.
tempDir = CreateTempDir();
Directory.Delete(tempDir);
Console.WriteLine("Directory.Delete: removed normal directory");
tempDir = CreateTempDir();
if (!RemoveDirectory(tempDir))
Console.WriteLine("RemoveDirectory: could not remove directory, error is " + Marshal.GetLastWin32Error().ToString());
else
Console.WriteLine("RemoveDirectory: removed normal directory");
Console.ReadLine();
}
}
}
Running this on my machine (win 7) I get the following output:
Directory.Delete: Access to the path 'C:\...\Local\Temp\a4udkkax.jcy' is denied.
RemoveDirectory Win32 error: 5
Directory.Delete: removed normal directory
RemoveDirectory: removed normal directory
We see we get error code 5, which, according to http://msdn.microsoft.com/en-gb/library/windows/desktop/ms681382(v=vs.85).aspx, is an Access Denied error.
I can then only assume that Explorer unsets the readonly attribute before deleting a directory, which is of course easily done. The command rmdir
also removes a directory marked as readonly.
As the documentation suggests the readonly flag should is not honoured on directories (even though it seems to be in Win 7), I would not rely on this behaviour. In other words I would not rely on readonly preventing anything.
removing readonly from folder, its sub folders and all the files in it
Almost, try:
var di = new DirectoryInfo("C:\\Work");
foreach (var file in di.GetFiles("*", SearchOption.AllDirectories))
file.Attributes &= ~FileAttributes.ReadOnly;
Related Topics
Find a File with a Certain Extension in Folder
Combobox Selecteditem VS Selectedvalue
Why Is Application.Restart() Not Reliable
Unblock File from Within .Net 4 C#
Why Can't Yield Return Appear Inside a Try Block with a Catch
Async Void, ASP.NET, and Count of Outstanding Operations
Finding Quoted Strings with Escaped Quotes in C# Using a Regular Expression
Async Process Start and Wait for It to Finish
C# - Realtime Console Output Redirection
Ef Code First: How to Get Random Rows
How to Call Generic Method with a Given Type Object
How to Make C# Switch Statement Use Ignorecase
How to Return Anonymous Type from Method
How to Catch a Specific SQLexception Error
Check If a String Contains an Element from a List (Of Strings)
Navigation Property Should Be Virtual - Not Required in Ef Core
Cannot Set Some Http Headers When Using System.Net.Webrequest