Answer the question
In order to leave comments, you need to log in
How to write a method correctly?
Hello!
There was a need to write a method that would delete one file from the directory at the specified path. Below are the options. Can't decide which one is the most appropriate in terms of readability and performance.
public static void ClearDirectory(string path)
{
var di = new DirectoryInfo(path);
foreach (var file in di.GetFiles())
file.Delete();
}
public static void ClearDirectory(string path)
{
var di = new DirectoryInfo(path);
di.GetFiles()[0].Delete();
}
public static void ClearDirectory(string path)
{
var di = new DirectoryInfo(path);
var _file = di.GetFiles()[0];
_file.Delete();
}
public static void ClearDirectory(string path)
{
new DirectoryInfo(path).GetFiles()[0].Delete();
}
Answer the question
In order to leave comments, you need to log in
do you have path contains the file name?
or just the target folder?
if it contains:
if not, you can clean up the entire folder
foreach (var f in Directory.EnumerateFiles(path, "*.*"))
File.Delete(f);
Do you really need to rely on the speed of deleting a file?
And the 1st method is the longest, because. it deletes all files in the folder, not just 1 file.
It is better to use EnumerateFiles if you need no more than one file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question