Reputation: 641
I need to delete the directory after its creation but I am getting an error because the directory is still in use by ruby.exe or another ruby process is there any way that I can close the directory like closing the file so that it will delete after its creation. When i reload the page and then try to remove the directory then the directory successfully delete.
Here is the code which i am trying
if Dir.exists?("first/test")
FileUtils.rm_rf("first/test")
FileUtils.mkdir("first/test")
else
Dir.mkdir("first/test")
end
Test folder does contain sub directories and files.
Upvotes: 1
Views: 1825
Reputation: 641
The stream was not closing after writing files in rubyzip class I have modified the code in rubyzip class like this
disk_file = File.open(diskFilePath, "rb")
io.get_output_stream(zipFilePath) { |f|
f.puts(disk_file.read())
}
disk_file.close
Upvotes: 2
Reputation: 3723
There are two main problems with your code, I think:
According to Ruby documentation, Dir.exists?
is deprecated and should not be used. Use Dir.exist?
(without the 's') instead;
You are trying to create a directory structure with FileUtils.mkdir
or Dir.mkdir
when, in fact, you need a 'stronger' method: FileUtils.mkdir_p
.
Try this:
if Dir.exist?("first/test")
FileUtils.rm_rf("first/test")
FileUtils.mkdir_p("first/test")
else
FileUtils.mkdir_p("first/test")
end
And see the corresponding documentation.
I believe that doing
FileUtils.mkdir("first")
FileUtils.mkdir("first/test")
would work fine, although I haven't tested it, because the second dir ('test') would be create inside an existing one. But if you need to create a whole structure in a single command you'd need the -p
flag using a bash command and the corresponding FileUtils.mkdir_p
method.
Let me also point you that this if..else
structure is not good this way. You want to create the directory structure in both if
and else
, and if the same command appears in both if
and else
, it must be taken out of the if..else
, like this.
if Dir.exist?("first/test")
FileUtils.rm_rf("first/test")
end
FileUtils.mkdir_p("first/test")
I hope this helps.
Upvotes: 1