The following codes works in windows:
//suppose I have a fname folder in c:\temp
mydir := "C:\\temp\\dname"
cmd, e := exec.Command("cmd", "/C", " rmdir /S /Q", mydir).Output()
But it will failed if there are spaces in the folder name, like:
mydir := "C:\\temp\
ame with space"
The Golang os.RemoveAll
can handle the folder name with spaces, but it will fail in the following situation:
C:\> mkdir myprj
C:\> cd myprj
C:\myprj> git init
//add some file
C:\myprj> git add .
C:\myprj> git commit -m "Add my files"
//
//This won't work
err := os.RemoveAll("C:/myprj")
Any ideas on how to remove a folder completely in windows using Go?
Either \\
or /
is the same error:
func main() {
if e := os.RemoveAll("c:\\temp\\myprj"); e != nil {
fmt.Println(e)
}
}
//OUTPUT
remove c:\temp\myprj\.git\objects\2b\018ef36e172ae05842a9326fc73f1c8baa3254: Access is denied.
But I can delete the folder with this command:
C:\> rmdir /S /Q c:\temp\myprj
// or from windows file explore without any problem
I found this method works well:
Create a batch file myrmdir.bat
: @echo off RMDIR /S /Q %1
Place this file in the same folder as the code and call it with: //Yes, I can use / instead of \\ and it works myfolder := "c:/temp/folder with space" exec.Command("cmd", "/C", "myrmdir.bat", myfolder).Run()
Hope this helps you. If you have a better solution(esp. pure Golang solution) please let me know.
I did the same thing on my windows and got the same error too. But I noticed the myprj folder is readonly (in properties) so I turned it off then the code works.
Actually every folder I created on c:\ is "readonly" by default.
And this is not apply to an empty folder the properties says "Read-Only (Only applies to files in folder)".