grozdeto
grozdeto

Reputation: 1379

How can I write to a file and remove the file afterwards in C#?

I need to create a file, write one line of text in the file and then delete the file and estimate how long it will take to do it.

Unfortunately, I am running in couple of problems, first I cannot write in the file, it succesfully creates it but nothing is written to it.

Secondly, I cannot delete the file because it has been used by another process.

Please help.

I have been trying to delete it for quite some time.

I have also tried wrapping it in usings, to no avail.

Writing to the file is the same situation. I even changed it so the file ends in .txt but that does not make any difference.

        public static void ProcessFile(string path)
        {
        string fullpath = path;
        int lastBracket = path.LastIndexOf("\\");
        // the filename does not contain .html so it can be named to .txt
        string newFileName = path.Substring(lastBracket + 1, path.Length - lastBracket - 6) + " hrefcount.txt";
        string newPath = Path.Combine(fullpath.Substring(0, lastBracket), newFileName);
        Console.WriteLine(newPath);
        int counter = 0;
            foreach (var line in File.ReadAllLines(path))
            {
                if (line.Contains("href="))
                {
                counter++;
                }
            }

        var fileCreated = File.CreateText(newPath);
        fileCreated.WriteLine("The number of times href appears is " + counter);
        Console.WriteLine();
        File.Delete(newPath);
    }

File created, nothing written to it, unable to delete due to has been used by another process.

Upvotes: 2

Views: 1728

Answers (4)

Christie
Christie

Reputation: 898

Instead of File.CreateText() use File.WriteAllText(path, content). It writes the text and then closes the file allowing you to delete it if necessary

Instead of the following

var fileCreated = File.CreateText(newPath);
fileCreated.WriteLine("The number of times href appears is " + counter);

You may write

File.WriteAllText(newPath, $"The number of times href appears is {counter}");

Refer documentation here

The issue with your approach is that CreateText() is used to write to a stream. But in your case, it is not necessary since you're writing all the text at once to the file and that text is small in size.

Upvotes: 3

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

File.Create() supports Dispose method which help you to release that file resource to perform further operations

To perform operations on file follow below steps:

  1. Create file and free up the resource using Dispose().

    File.Create(newPath).Dispose();

or Use StreamWriter to create file and write text to it.

using( StreamWriter sw = new StreamWriter(newPath, true)
{
   sw.Write($"The number of times href appears is {counter}"); //Used string interpolation 
}

StreamWriter calls Dispose() function to release file resource.

When Writer release control over file, then you will not face issue related to I cannot delete the file because it has been used by another process.

Now you can delete file using,

  1. File.Delete(newPath);

MSDN : IDisposable.Dispose Method

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

Upvotes: 1

Steve
Steve

Reputation: 216293

The cause of your error is the fact that you don't close and dispose the variable fileCreated. This, is a FileStream and until you close and dispose this variable the file is not available to anyone, even your own code that has opened the file.

So the first thing to do is

using (var fileCreated = File.CreateText(newPath))
{
    fileCreated.WriteLine("The number of times href appears is " + counter);
}

The using block ensure the proper disposal of the variable.

However there are other parts of your code that you can simplify

public static void ProcessFile(string path)
{
    string folder = Path.GetDirectoryName(path);
    string file = Path.GetFileName(path);


    // Keep the first 6 characters from the source file?
    string newFile = file.Substring(0, 6) + " hrefcount.txt";
    string newPath = Path.Combine(folder, newFile);

    // A single line to retrieve your counter thanks to IEnumerables and Linq
    int counter = File.ReadLines(path).Count(x => x.Contains("href="));

    // Create, but dispose also the file
    using (var fileCreated = File.CreateText(newPath))
    {
        fileCreated.WriteLine("The number of times href appears is " + counter);
    }

    // Now you should be free to delete the file
    File.Delete(newPath);
}

Upvotes: 1

Oshawott
Oshawott

Reputation: 540

I cannot delete the file because it has been used by another process.

Probably you're not disposed your files after creating. To do that, you should additionally use FileStream.Dispose method:

File.Create(path).Dispose();


estimate how long it will take to do it

You can use System.Diagnostics.Stopwatch class to do that:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
/*
   do the magic
*/
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);


You can use File.WriteAllText method instead of File.CreateText to write your text to file:

File.WriteAllText(path, myText);

Remember that since the .NET 4 you can use this method with array or List<T> too instead of string.

Upvotes: 1

Related Questions