-4

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?

Mukhcora
  • 1
  • 1
  • 1
  • what are you trying to do here exactly? – Cris Dec 30 '13 at 13:07
  • By catching the offending exception and alerting the user? What exactly are you asking here? – lc. Dec 30 '13 at 13:07
  • i am going to open a batch file and write this file – Mukhcora Dec 30 '13 at 13:08
  • possible duplicate of [How to prevent my C# application from opening the same file twice](http://stackoverflow.com/questions/3444045/how-to-prevent-my-c-sharp-application-from-opening-the-same-file-twice) – Brian Dec 30 '13 at 14:10

1 Answers1

10

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you.. it works :) can you tell me what is the problem in my previous code – Mukhcora Dec 30 '13 at 13:14
  • @Mukhcora: As I said, your `File.Create` call opens the file, and you've kept it open - so when you try to open it again, you're getting the exception. – Jon Skeet Dec 30 '13 at 13:28