The process cannot access the file because it is being used by another process error

here is my code:

public static bool createFile(string dir) {
        dir="c:\\e.bat";
        System.IO.File.Create(dir);


            if (System.IO.File.Exists(dir))
            {
                try
                {
                    StreamWriter SW;
                    SW = System.IO.File.CreateText(dir);
                    SW.WriteLine("something ");
                    SW.Close();
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                    Console.ReadLine();
                    return false;
                }                    
            }
            return true;            
    }

here dir is the current directory. i am facing the error The process cannot access the file because it is being used by another process.how can i solve this problem?

Jon Skeet
people
quotationmark

You're calling File.Create at the start of the method - which is returning you a stream, which stays open. It's not clear why you're calling that at all, but I'd suggest just removing that line.

You should also use a using statement, only catch specific exceptions, use appropriate using directives, and follow .NET naming conventions. For example:

using System.IO;

...

public static bool CreateFile(string file)
{
    using (var writer = File.CreateText(file))
    {
        try
        {
            writer.WriteLine("something ");
        }
        catch (IOException e)
        {
            // TODO: Change the handling of this. It's weird at the moment
            Console.Write(e.Message);
            Console.ReadLine();
            return false;
        }
    }
    return true;            
}

I've removed the check for the file existing, as with the previous code it would always exist because you'd just created it.

You should also consider using File.WriteAllText as a simpler way of writing the file.

people

See more on this question at Stackoverflow