File.Delete Access to the path is denied

前端 未结 5 915
无人共我
无人共我 2021-01-18 05:26

My console application program is creating some runtime files while it is working so what I want to do is delete all of these files on the application startup. I have tried

相关标签:
5条回答
  • 2021-01-18 06:02
    if (File.Exists(filePath))
    {
        File.SetAttributes(filePath, FileAttributes.Normal);
        File.Delete(filePath);
    }
    
    0 讨论(0)
  • 2021-01-18 06:05

    Try using the Microsoft.VisualBasic.FileIO.FileSystem methods as it has a handy DeleteDirectory method, I had access troubles awhile ago and this was the fix for my problem.

    var directory = new DirectoryInfo(targetDir);
    if (directory.Exists)
    {
        Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
    }
    
    0 讨论(0)
  • 2021-01-18 06:06

    Using Windows API MoveFileEx might be a potential solution with a parameter MOVEFILE_DELAY_UNTIL_REBOOT to remove the file only after reboot.

    Please check http://msdn.microsoft.com/en-us/library/aa365240%28v=vs.85%29.aspx.

    0 讨论(0)
  • 2021-01-18 06:15

    You say that the files are not open in another application, but it must be open within your application:

    //Create some directories to delete
    Directory.CreateDirectory("C:/Temp/DeleteMe");
    Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
    File.Create("C:/Temp/DeleteMe/DeleteMeFile");//FileStream still open!!
    
    //Delete the files
    var directory = new DirectoryInfo("C:/Temp/DeleteMe");
    if (!directory.Exists) return;
    foreach (FileInfo file in directory.GetFiles())
    {
        file.Delete();
    }
    foreach (DirectoryInfo dir in directory.GetDirectories())
    {
        dir.Delete(true);
    }
    

    Make sure you dispose the file stream when you create the file

    //Create some directories to delete
    Directory.CreateDirectory("C:/Temp/DeleteMe");
    Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
    using (File.Create("C:/Temp/DeleteMe/DeleteMeFile")) { }
    
    //Delete the files
    var directory = new DirectoryInfo("C:/Temp/DeleteMe");
    if (!directory.Exists) return;
    foreach (FileInfo file in directory.GetFiles())
    {
        file.Delete();
    }
    foreach (DirectoryInfo dir in directory.GetDirectories())
    {
        dir.Delete(true);
    }
    
    0 讨论(0)
  • 2021-01-18 06:16

    I got this error and found that it was because my test files were readonly. Changed this and I can now use fileinfo to delete them no worries.

    0 讨论(0)
提交回复
热议问题