删除文件夹中文件的只读属性

人气:662 发布:2022-09-22 标签: asp.net ASP.NET

问题描述

在我的应用程序中,我将文件从一个文件夹移动到另一个文件夹 复制到目标文件夹,我正在从源文件夹中删除文件

 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(); } } 

当我这样做时,我收到一条错误消息拒绝访问该文件。然后我手动删除了只读属性。我想知道如何通过代码完成。 请帮助。

解决方案

做点什么如下所示,以递归方式清除指定父目录中所有目录和文件的readonly(和archive等)。

 < span class =code-keyword> 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); } } } 

因此您可以这样称呼:

  public   void  Main() { DirectoryInfo parentDirectoryInfo = < span class =code-keyword> new  DirectoryInfo( @  c:\ test);  ClearReadOnly(parentDirectoryInfo); } 

试试这个:

 FileInfo fi =  new  FileInfo(path);  fi.IsReadOnly =  false ;  fi.Refresh(); 

使用 filename.IsReadOnly = false ;

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

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.

解决方案

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);
}

Try this:

FileInfo fi = new FileInfo(path);
fi.IsReadOnly = false;
fi.Refresh();

Use filename.IsReadOnly = false;

418