Author Options:

How do you have a C# program look for a file in a directory and if it isnt there generate it? Answered

I would like it to check for a text file named Username.txt in the same drive (ex C:/) as the program, and if it isnt there, generate it? Where in the source would the code go?


All done using the System.IO namespace and it is very easy to do what you are asking.  There are a few different ways to do it. I'll show you one.

A method is built in called "File.Exists()" which will check to see if a given file exists on your system. 

You could put this in a IF statement kinda like this:

 if (File.Exists("C:\\testfile.txt"))
   return true;
 static void WriteToFile()
   StreamWriter SW;
   SW.WriteLine("This is the first line of text");
   SW.WriteLine("This is second line");
   Console.WriteLine("File Created Successfully");

Note that you should also build in some simple error checking (using try, catch) to make sure the file is actually created without error.

Where you put this code depends on when you want it to run.  If you want to provide more detail around what you're trying to do I could write up a simple example for you to work with.

Dead easy to write it, what do you mean where in the source would it go ? It goes where you need it !