Delete folder with C# code? - c#

I am trying to delete a folder but i can manage to get it right?
The folder i am trying to delete is called ExtractedFiles and it is inside a folder called FormValue.
I can delete a spreadsheet in the same FormValue folder but cant delete the folder.
I think the problem might be that i don't have the right file extension for the folder
This works:
if (File.Exists(tempFolderPathAlt + saveas + ".xls"))
{
File.Delete(tempFolderPathAlt + saveas + ".xls");
}
This does not work:
if (File.Exists(tempFolderPathAlt + "ExtractedFiles"))
{
File.Delete(tempFolderPathAlt + "ExtractedFiles");
}
Could someone please tell me the file extension of a folder or how to delete one?

If you want to delete a folder, you should use Directory.Delete instead of File.Delete:
String path = Path.Combine(tempFolderPathAlt, "ExtractedFiles");
bool directoryExists = Directory.Exists(path);
if(directoryExists)
Directory.Delete(path, true); // deletes sub-directories

Try using the Directory.Delete method.

you want
Directory.Delete
Since your deleting a folder and not a file

For deleting dirrectories, you need to use the method
Directory.Delete(string path,
bool recursive);
Refer official docs here:
http://msdn.microsoft.com/en-us/library/fxeahc5f.aspx

Check this out if you are getting IOException deleting directories :
Cannot delete directory with Directory.Delete(path, true)

Related

Moving Uploaded Files to Another Folder [duplicate]

I've got a folder:
c:\test
I'm trying this code:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test");
I get exception:
File already exists
The output directory definitely exists and the input file is there.
What you need is:
if (!File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Delete(#"c:\test\Test\SomeFile.txt");
}
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
This will either:
If the file doesn't exist at the destination location, successfully move the file, or;
If the file does exist at the destination location, delete it, then move the file.
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt.
You need to move it to another file (rather than a folder), this can also be used to rename.
Move:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
Rename:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\SomeFile2.txt");
The reason it says "File already exists" in your example, is because C:\test\Test tries to create a file Test without an extension, but cannot do so as a folder already exists with the same name.
Personally I prefer this method.
This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = #"c:\test\SomeFile.txt";
string destination = #"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
You can do a P/Invoke to MoveFileEx() - pass 11 for flags (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
Or, you can just call
Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
after adding Microsoft.VisualBasic as a reference.
With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:
In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.
Source: Microsoft Docs
For all other versions of .Net, this answer is the best. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)
If file really exists and you want to replace it use below code:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.
Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.
Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = #"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(#"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension.
It splits the file in two before the extension, attaches "_copy." in between.
This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)

Unable to delete file after moving in c#

I am trying to delete a file but I am getting error message (access denied) even though I have full permission. Initially my file will be in my root folder. First I am renaming the file and then moving the file to a different folder (outside of root folder) as below.
System.IO.File.Move(strPhysicalFolder+ tpfile,strPhysicalFolder+fName);
System.IO.File.Move(strPhysicalFolder + fName, filePath + fName);
System.IO.File.SetAttributes(filePath + fName, FileAttributes.Normal);
Now whenever I try to delete the file I am getting an error (access denied).
Below is my code:
string strFileFullPath = srcPath + filename;
if (System.IO.File.Exists(strFileFullPath))
{
System.IO.File.Delete(strFileFullPath);
}
strFileFullPath contains the path to the file I am not able to delete. Do I need to do anything before deleting (setting attribute)? Any help would be appreciated. Thank you.
Sounds daft but it will probably be the permissions on the folder.
maybe something like the following:
System.IO.File.SetAttributes(strFileFullPath, FileAttributes.Normal);
System.IO.File.Delete(strFileFullPath);

Rename existing file name

I have the following code which copies a file to a specific folder and then renames it.
When a file with that name already exists I get the following exception:
Cannot create a file when that file already exists
Is there a way to overwrite the file and rename it? or I should delete the old one and then change the name?
Here is my code:
File.Copy(FileLocation, NewFileLocation, true);
//Rename:
File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));
Try to use only:
if (File.Exists("newfilename"))
{
System.IO.File.Delete("newfilename");
}
System.IO.File.Move("oldfilename", "newfilename");
One simple option is to delete the file if it exists:
if (System.IO.File.Exists(newFile)) System.IO.File.Delete(newFile);
System.IO.File.Move(oldFile, newFile);
Something like that should work.
You're correct, File.Move will throw an IOException if/when the filename already exists. So, to overcome that you can perform a quick check before the move. e.g.
if (File.Exists(destinationFilename))
{
File.Delete(destinationFilename);
}
File.Move(sourceFilename, destinationFilename);
You should use File.Exists rather than letting the Exception throw. You can then handle if the file should be overwrote or renamed.
Step 1 : as a first step identify wether the file exists or not before copying the file.
using File.Exists() method
Step 2: if the file already exists with same name then delete the existing file using File.Delete() method
Step 3: now copy the File into the new Location using File.Copy() method.
Step 4: Rename the newly copied file.
Try This:
string NewFilePath = Path.Combine(NewFileLocation, fileName);
if(File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
//Now copy the file first
File.Copy(FileLocation, NewFileLocation, true);
//Now Rename the File
File.Move(NewFilePath, Path.Combine(NewFileLocation, "File.txt"));
I always use MoveFileEx with the flag MOVEFILE_REPLACE_EXISTING.
Limitations:
It needs to use PInvoke, so it means your code will only work on the Windows platform.
This flag MOVEFILE_REPLACE_EXISTING only work with File(Doesn't work with Folder)
If lpNewFileName or lpExistingFileName name a directory and lpExistingFileName exists, an error is reported.

File.Move Does Not Work - File Already Exists

I've got a folder:
c:\test
I'm trying this code:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test");
I get exception:
File already exists
The output directory definitely exists and the input file is there.
What you need is:
if (!File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Delete(#"c:\test\Test\SomeFile.txt");
}
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
This will either:
If the file doesn't exist at the destination location, successfully move the file, or;
If the file does exist at the destination location, delete it, then move the file.
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt.
You need to move it to another file (rather than a folder), this can also be used to rename.
Move:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
Rename:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\SomeFile2.txt");
The reason it says "File already exists" in your example, is because C:\test\Test tries to create a file Test without an extension, but cannot do so as a folder already exists with the same name.
Personally I prefer this method.
This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = #"c:\test\SomeFile.txt";
string destination = #"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
You can do a P/Invoke to MoveFileEx() - pass 11 for flags (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
Or, you can just call
Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
after adding Microsoft.VisualBasic as a reference.
With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:
In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.
Source: Microsoft Docs
For all other versions of .Net, this answer is the best. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)
If file really exists and you want to replace it use below code:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.
Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.
Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = #"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(#"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension.
It splits the file in two before the extension, attaches "_copy." in between.
This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)

How to replace a directory with the same name with new one?

I am putting a check that if a directory by a name exists then it should delete that directory and replace it with the new one.
For that i am having this code:
if (Directory.Exists(b))
{
Directory.Delete(b);
Directory.CreateDirectory(b);
}
where b is the name of the directory for which i am outting the check.
I am getting a run time error that
Directory is not empry, what shall i do?
Try Directory.Delete(b, true)
If the directory isn't empty you'll need to go in enumerate all the files and delete those first.
You'll also have to recurse down any subfolders too.
Or just call Directory.Delete(folder, true) of course!
You must call Directory.Delete(path, true) to force the deletion of subdirectories and files.
Delete subdirectories and files by setting a second boolean parameter to true:
if (Directory.Exists(b))
{
Directory.Delete(b, true);
Directory.CreateDirectory(b);
}

Categories

Resources