C# file delete and take long time to release process - c#

Delete file using C# from directory is holding the process for long time. How to kill process once the file is deleted.
Tried with 2 options of deleting the file,
Option 1:
path = #"C:\temp\a.xml";
File.Delete(path);
Option 2:
path = #"C:\temp\";
DirectoryInfo CVfiles = new DirectoryInfo(path);
foreach (FileInfo CVfile in CVfiles.GetFiles())
{
CVfile.Delete();
}
Update
(from clarification in comments)
path = #"C:\temp\a.xml";
DirectoryInfo CVfiles = new DirectoryInfo(path);
foreach (FileInfo CVfile in CVfiles.GetFiles())
{
CVfile.Delete();
}
Thanks,

You could try
C# delete a folder and all files and folders within that folder
Ultimately the deletion will take as much as deletions needs.
How to kill process once the file is deleted.
You can just exit the program.

Related

C# Is there a faster way to speed up copying a directory and files inside?

I'm using below code to make a copy a folder available on a network. This folder has, subfolders and files with total of 455 files and 13 folders and of size 409 MB.
My method is recursively calling itself to create a copy of sub folders and files in it. Overall, this method is taking more than 10 minutes to finish the task and I'm looking to speed up the process.
So far, I've went through different posts but did not find any better solution. Is there a better way to achieve my task or any improvements to my code for a faster execution?
void CopyDirectoryAndFiles(string sourceDirectory, string destinationDirectory, bool recursive)
{
// Get information about the source directory
var dir = new DirectoryInfo(sourceDirectory);
// Check if the source directory exists
if (!dir.Exists)
throw new DirectoryNotFoundException($"Source directory not found:dir.FullName}");
// Cache directories before we start copying
DirectoryInfo[] dirs = dir.GetDirectories();
// Create the destination directory
Directory.CreateDirectory(destinationDirectory);
// Get the files in the source directory and copy to the destination directory
foreach (FileInfo file in dir.GetFiles())
{
string targetFilePath = Path.Combine(destinationDirectory, file.Name);
file.CopyTo(targetFilePath);
}
// If recursive and copying subdirectories, recursively call this method
if (recursive)
{
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDirectory= Path.Combine(destinationDirectory,subDir.Name);
CopyDirectoryAndFiles(subDir.FullName, newDestinationDirectory, true);
}
}
}
Thanks for your help.
I don't think there's a way to increase performance in a drastic way, but I can suggest a few things to try:
replace foreach w/ Parallel.ForEach to copy data in several streams;
you can use an external tool (e.g. xcopy), which is optimized for the task, and call this tool from your C# code. xcopy can copy folders recursively if you specify the /e flag.

C# to copy files from one folder to another without duplicates

Im trying to copy files from "source" folder to my "destination" folder, without duplicates. I cant use destination folder to compare as it will eventually get deleted from there. I had gotten help here to make a batch file
Robocopy "source" "destination" "*chr.txt*" "*hdr.txt*" /M
that uses attribute to keep track of files copy before. However I need to do this in C# instead. I know theres command to copy
System.IO.File.Copy(sourceFile, destFile, true);
but not sure how to go about being specific on file name "*chr.txt" and taking care of duplicates.
I need to do this in C# instead
Process.Start("robocopy", "source destination chr.txt hdr.txt /M");
Here is a method I created a while ago that has worked well for me (aside from the checking for duplicates part that I just added and haven't tested). Let me know if any parts of it do not work for what you need.
private static void CopyDirectory(string from, string to)
{
var toFileNames = new DirectoryInfo(to)
.GetFiles()
.Select(f => f.Name)
.ToList();
var directory = new DirectoryInfo(from);
var files = directory.GetFiles();
foreach (var file in files)
if (!toFileNames.Contains(file.Name))
file.CopyTo(Path.Combine(to, file.Name));
var subDirectories = directory.GetDirectories();
foreach (var subDirectory in subDirectories)
{
var newDirectory = Directory.CreateDirectory(Path.Combine(to, subDirectory.Name));
CopyDirectory(subDirectory.FullName, newDirectory.FullName);
}
}

C# using filestream instead of file.copy

I am using File.copy to copy some files.
The problem is, it copies files asynchronus so it continues the program while still copying some files.
Now i got the tip to use filestream instead of file.copy.
The code i use now is: (example)
string instdir = (#"C:\test.dll");
string srcdir = #"C:\test1.dll";
File.Copy(srcdir, instdir, true);
The problem with this is, the "test.dll" value is read from a xml file (so there are much more files to copy)
After the copy it should execute an .exe file, but it executes the file before everything is copied and that is giving the error.
Any tips?
I also have the next question:
I got a solution for above, this is a single file copy.
Now i also have this one:
public static void CopyFolder(DirectoryInfo source, DirectoryInfo install)
{
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFolder(dir, install.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(install.FullName, file.Name), true);
}
for multi file copy (copy everything in folder)
Any idea how to use it in that?
Thanks!
So you can open two streams and copy the streams:
using(var src = File.OpenRead(#"srcPath"))
using(var dest = File.OpenWrite(#"destPath"))
{
src.CopyTo(dest); //blocks until finished
}

Deleting directories inside directories

I know that if you want to delete a directory you have to delete all of it's files first.
However if you want to delete a directory which contains empty sub-directories, do you have to delete those sub-directories first? or can you just go ahead and delete the main directory?
Directory.Delete set the recurse flag to true, should do the job, no need to empty them first.
Directory.Delete(path, true);
I have just noticed that your tag refers to IsolatedStorage, in which case you will need to enumerate all the files and folders and delete as you go.
How to: Delete Files and Directories in Isolated Storage
You can try to delete recursively:
var path = Path.GetFullPath(#"C:\Temp\DeleteMe");
Directory.Delete(path,true); // true for recursive
This should delete everything including files if you have the proper permissions.
Why check if it is empty or not when you are going to delete it anyway.
You can use the Directory.Delete(yourpath,true) method only if you are sure that there isn't any readonly file in the directory. else it will throw an exception. Instead you can use your own recursive method like this which will first mark the file as normal before deleting it.
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}

Unable to Delete Folder Containing Invisible Files

Using Visual Studio 2010 C#. I'm attempting to delete a folder in C:/Windows/MyFolderA where MyFolderA is a folder placed there by my software - Not Microsoft's.
I've used this code to delete the contents of the folder and the folder itself:
foreach (FileInfo tempfi in listOfMSIInstallers)
{
//Delete all Files
DirectoryInfo localDirectoryInfo = new DirectoryInfo(targetDirectory);
FileInfo[] listOfMSIInstallers = localDirectoryInfo.GetFiles("*",SearchOption.AllDirectories);
File.SetAttributes(tempfi.FullName, File.GetAttributes(tempfi.FullName) & ~FileAttributes.ReadOnly); //Remove Read-Only
File.Delete(tempfi.FullName); //Delete File
string parentFolderPath = "C:/Windows/MyFolderA"; //Example string for StackOverflow
//Remove ReadOnly attribute and delete folder
var di = new DirectoryInfo(parentFolderPath);
di.Attributes &= ~FileAttributes.ReadOnly;
Directory.Delete(parentFolderPath);
}
If I attempt to delete the folder I get an exception
"System.IO.IOException: The directory is not empty".
Showing invisible files on my GUI I do not see any. Looking at the folder with a command prompt there appears to be 2 directories: 1 named . and the second named .. (not too familiar with command prompt dir so I don't know if they're temp names or if those are the actual directory names) both at 0 files and 0 bytes.
Debugging through looking at the FileInfo[] object, it doesn't grab the invisible files found from command prompt.
Any ideas how I can delete the files/directory?
Try
Directory.Delete(parentFolderPath, true);

Categories