Click here to Skip to main content
16,012,082 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

In my application I am moving files from one folder to another

When copied to target folder, I am deleting files from source folder

C#
filepath= Path.GetExtension(source + "\\" + fi.Name);
if (filepath == ".csv" || filepath == ".xls" || filepath == ".xlsx")
{
    if (!File.Exists(target + "\\" + fi.Name))
   {
                                
         fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
         fi.Delete();
   }
}


When I do so, I am getting an error says 'Access denied to the file'. And then I manually removed read-only property. I want to know how it can be done through code.

Please help.
Posted

Try this:
C#
FileInfo fi = new FileInfo(path);
fi.IsReadOnly = false;
fi.Refresh();
 
Share this answer
 
Comments
Rakshith Kumar 11-Nov-13 23:47pm    
Nice one 5+
Do something like the following to recursively clear readonly (and archive, etc.) for all directories and files within a specified parent directory.

C#
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:
C#
public void Main()
{
    DirectoryInfo parentDirectoryInfo = new DirectoryInfo(@"c:\test");
    ClearReadOnly(parentDirectoryInfo);
}
 
Share this answer
 
Use

filename.IsReadOnly = false;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900