We help IT Professionals succeed at work.

How to properly create a blank file in C#?

bemara57
bemara57 asked
on
I'm trying to create a blank text file in one of my onclick events. This is what I did:

string someName = @"C:\Temp\test.txt";

                if (!File.Exists(someName))
                {
                    try
                    {
                        File.CreateText(someName);                        
                    }
                }

It creates the file but I can't open it. It says it's being used by another process. Seems that it's locked. It has the right inherited permissions so it's not that. Do I have to do something extra? Another method need to write to it shortly after and am having trouble.
Comment
Watch Question

Top Expert 2007
Commented:
This method creates a StreamWriter, which you are not closing. So, try the code below, and it should be OK.

Jim

try
{
  StreamWriter sw = File.CreateText(someName);
  sw.Close();                        
}

Open in new window

Rahul Goel ITILSenior Consultant - Deloitte
BRONZE EXPERT
Commented:
use this code
using(TextWriter temp = new StreamWriter(@":\Temp\test.txt",FileMode.Create){}

It will create the file and will close that time as well.


Using sw As StreamWriter = New StreamWriter("newfile.txt")
            ' Add some text to the file.
            sw.Write("This is the ")
            sw.WriteLine("header for the file.")
            sw.WriteLine("-------------------")
            ' Arbitrary objects can also be written to the file.
            sw.Write("The date is: ")
            sw.WriteLine(DateTime.Now)
            sw.Close()
        End Using

Open in new window

Author

Commented:
Thanks all, it worked great. I ended up using:

                        using (StreamWriter sw = File.CreateText(file))
                        { sw.Close(); }

I figured this would take care of the dispose as well. Although I don't think I need to explicitly close it since the using theoretically takes care of it. By the way, do I have to do this for copying files as well? Because I also have this in my code where I need to write to file2 shortly after:

File.Copy(file1, file2, false);
Top Expert 2007

Commented:
That one does not return a stream, so you will be OK.

Jim