tags:

views:

416

answers:

3

revised!

I want to create a file say called test.txt.

if that file already exists I want to create file called test1.txt and so on.

+17  A: 

Pass in FileMode.Create to File.Open(string, FileMode) when opening the file and it will create a new file every time.

FileStream file = File.Open("text.txt", FileMode.Create);
Samuel
+1 This is the best solution.
Andrew Hare
A: 

Here is a short example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
     String file = "text.txt"; 

     if (File.Exists(file))
      File.Delete(file);

     FileStream fs = File.Create(file);
    }
}
Andrew Hare
You shouldn't use File.Exists for this. Who's to say something doesn't create a file in between File.Exists, File.Delete and File.Create?
Samuel
Good point - I like your solution better! :)
Andrew Hare
+1  A: 

The classes in System.IO should help you do that.

FileStream fs = System.IO.File.Create(fileName);
Erich Mirabal