D
D
Dmitry Bystrov2018-07-18 16:40:44
C++ / C#
Dmitry Bystrov, 2018-07-18 16:40:44

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.

Method #1
public static void ClearDirectory(string path)
{
    var di = new DirectoryInfo(path);
    foreach (var file in di.GetFiles())
        file.Delete();
}
Method #2
public static void ClearDirectory(string path)
{
    var di = new DirectoryInfo(path);
    di.GetFiles()[0].Delete();
}
Method #3
public static void ClearDirectory(string path)
{
    var di = new DirectoryInfo(path);
    var _file = di.GetFiles()[0];
    _file.Delete();
}
Method #4
public static void ClearDirectory(string path)
{
    new DirectoryInfo(path).GetFiles()[0].Delete();
}

The screenshot below shows the average execution time for each method. As you can see, the last two have the lowest result.
5b4f423d2e612167876396.png
Need advice. Which of these methods is preferable to use?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
#
#, 2018-07-18
@Teshuhack

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);

or the first one in the folder
and you can also bang the folder, with all the contents (this is just approved by the second parameter)
.. and then recreate ... never thought - what is faster in the end? ))

N
Nikita, 2018-07-18
@Smiz001

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.

A
ApeCoder, 2018-07-18
@ApeCoder

It is better to use EnumerateFiles if you need no more than one file.

B
basrach, 2018-07-21
@basrach

Ha!
Methods #2, #3 and #4 are exactly the same, but the results in the table for #2 differ from the last ones by 6 times.
This means that your measurements are only good for wiping something.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question