Search code examples
c#visual-studiotext

Creating and Editing Text Files in a Demo C# code resulting in a "Used by another Process" Error


I just started learning to code in C# with Visual Studio and I wanted to mess around trying to make and edit text files, but as I am trying to do it, this always comes up at "File.WriteAllLines(filePath, lines);"

System.IO.IOException: 'The process cannot access the file 'C:\Users\Brian\Documents\Test.txt' because it is being used by another process.'

I tried looking through the task manager to see if any other processes are interfering or using the text file, but I could not find any. I attached the very basic console code below. Any fixes?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TextFileDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\Users\Brian\Documents\Test.txt";
            File.Create(filePath);
            List<string> lines = new List<string>();

            lines.Add("Hello");
            lines.Add("This is a Text File");
            File.WriteAllLines(filePath, lines);

            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }
    }
}

Solution

  • It think it quite likely it's your own File.Create call. It's unnecessary - take it out; File.WriteAllLines will create the file. You'd use File.Create when you wanted to capture the returned FileStream and write data to it (writing data to the filestream causes data to be written to the file). As you don't capture the stream, there's no point calling Create, and the still-open stream hanging around some milliseconds later when you're trying to WriteAllText is causing the issue. If you do want to use File.Create in future it should be via a pattern like:

    using(var fs = File.Create(...){
      //use fs in here to write the file
    }
    //c# will dispose of the filestream here
    

    ..but for this code (and even, future code) it's easier just to use WriteAllXxx and AppendAllXxx if you can